C# SQL insert query syntax error with MS Access - c#

I am trying to perform an insert query in C# but it keeps telling me syntax error in insert into statement.
Here is my query:
Checks.SQL.Insert(mydb, "SELECT * FROM Employee", "INSERT INTO Employee(First_Name,Last_Name,Email,CellPhone_Number,TypeOfUser,Username,Password) VALUES('" + txtFirstName.Text + "','" + txtLastName.Text + "','" + txtEmail.Text + " ', '" + txtCellphone.Text + "'," + typeId + ",'"+Encrypcion.encrypt(txtUsername.Text)+"','"+Encrypcion.encrypt(txtPassword.Text)+"' )");
Here is my checks insert function
public static void Insert(OleDbConnection mydb, string SelectQuery, string InsertQuery)
{
mydb.Open();
OleDbDataAdapter query2 = new OleDbDataAdapter(SelectQuery, mydb);
OleDbCommand cmd = new OleDbCommand(InsertQuery, mydb);
query2.InsertCommand = cmd;
query2.InsertCommand.ExecuteNonQuery();
mydb.Close();
}
Here is a picture of my InsertQuery with input data as example:
enter image description here
See a picture of my table info:

Password is a reserved word in Access, so:
"INSERT INTO Employee(First_Name,Last_Name,Email,CellPhone_Number,TypeOfUser,Username,[Password]) .."

Related

how to handle the exception Implicit conversion from data type varchar to varbinary(max) is not allowed. while adding the data to database

In my application i need to add data to database and display it in gridview below is the code that i used without adding id it works fine but after adding Id in my insert query and update query i am getting this exception as Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query.How can i handle this exception as i am new to this
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["sqlconnection "].ConnectionString;
cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from TableName";
cmd.Connection = cnn;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, " TableName ");
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataRow drow = ds.Tables["TableName"].NewRow();
drow["id"] = TextBox1.Text;
drow["Name"] = TextBox2.Text;
drow["Designation"] = TextBox3.Text;
drow["Mobile_No"] = TextBox4.Text;
drow["Address"] = TextBox5.Text;
ds.Tables["TableName "].Rows.Add(drow);
da.Update(ds, " TableName ");
string script = #"<script language=""javascript"">
alert('Information have been Saved Successfully.......!!!!!.');
</script>;";
Page.ClientScript.RegisterStartupScript(this.GetType(), "myJScript1", script);
}
Since Id is most probably a numeric value, don't try to assign it a string value, instead generate the SQL code for the number:
"[...]values(" + Id + ",'" + [...]
instead of (pay attention to the ' sign)
"[...]values('" + Id + "','" + [...]
However, as Damien_The_Unbeliever pointed out, you should use SQL Parameters instead of writing the whole statement as string.
If your Id value is defined as auto-assigned identity column, just remove it from the value list of your statement.
The exception is Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query.
So either both Sql server table column and C# id column must be varchar or varbinary.
VarBinary(sqltype)=Byte[] (.Net)
byte[] ID=SqlDbType.VarBinary;
string query = "insert into RegistrationDetails1(Id,FirstName,LastName,MiddleName,Email,LoginID,CreatedDate,Role,Password,Activestatus,passwordstatus,Dept,Eno,Customer) values('" + ID + "','" + txtfname.Text + "','" + txtlname.Text + "','" + txtmname.Text + "','" + txtEmail.Text + "','" + LoginId[0].ToString() + "','" + DateTime.Now + "','" + ddlRole.SelectedItem.ToString() + "','" + Password + "','" + "1" + "','" + "1" + "','" + Dept + "','" + txteno.Text + "','" + Customer + "')";

I am getting 'System.Web.UI.WebControls.TextBox' into sql table instead of getting actual data entered in text boxes

Can someone please help me figure out why I am getting 'System.Web.UI.WebControls.TextBox' in MySQL database instead of actual values being entered in the text field. The code I am using is below ..
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
string queryStr;
string connString=System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnectionString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "";
queryStr = "INSERT INTO seework.userdata (First_Name, Middle_Name, Last_Name, Email_Address, Phone_Number, Username, Password)" + "VALUES('" + firstnameTextBox + "','" + middlenameTextBox + "','" + lastnameTextBox + "','" + emailaddressTextBox + "','" + phonenoTextBox + "','" + usernameTextBox + "','" + passwordTextBox + "')";
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
cmd.ExecuteReader();
conn.Close();
I have tried all I could but still no luck. Any help would be really appreciated.
Thanks in Advance!
You are passing the TextBox itself to the database using the query. You need to pass the text instead. For this you can use .Text property of the TextBox control. Which gives you the Text/Content inside the Textbox Control. And one more advise for you. Use Parameterized queries instead for cuch queries to avoid Sql Injection.
For example:
queryStr = "INSERT INTO seework.userdata (First_Name, Middle_Name)VALUES(#fName,#mName)";
SqlCommand cmd = new SqlCommand(queryStr);
cmd.Parameters.Add("#fName",SqlDbType.VarChar).Value=firstnameTextBox.Text ;
cmd.Parameters.Add("#mName",SqlDbType.VarChar).Value=middlenameTextBox.Text;
// Build your command like this
// Execute the command then
you should use .Text after the name of TEXTBOX.
For Example :-
string insert = "insert into table_Name (Name, Contact, Email) values ('" + txtname.Text + "', '" + txtcontact.Text + "', '" + txtemail.Text + "')";

SqlCeCommand keeps giving me an exception

I am connecting to a compact SQL database server through a WCF service and keep getting the following except on the Command.ExecuteNonQuery(). I have tried fixing this but just don't know what's wrong.
The exception:
An exception of type 'System.Data.SqlServerCe.SqlCeException' occurred
in System.Data.SqlServerCe.dll but was not handled in user code
The code:
//The connectionString can be found in the properties table of the database
string connString = "Data Source=C:\\Users\\User\\documents\\visual studio 2012\\Projects\\ADO_LINQ\\ADO_LINQ\\App_Data\\MyDatabase.sdf;Persist Security Info = False";
SqlCeConnection myConnection = new SqlCeConnection(connString);
myConnection.Open();
// Create the query
string myQuery = "INSERT INTO Player " +
" VALUES (" + registrationID + "," +
firstName + ", " +
lastName + ", " +
phoneNumber + ", " +
address + ", " +
dateOfBirth + ");";
//Initialuze the command
SqlCeCommand myCommand = new SqlCeCommand(myQuery, myConnection);
//Run the command
myCommand.ExecuteNonQuery();
//Close the connection
myConnection.Close();
You are missing Single quotes around your string data types, Assuming only registrationID is Integer data type and all other columns are String data type , your query should look something like ......
// Create the query
String myQuery = "INSERT INTO Player " +
" VALUES (" + registrationID + ", '"+ firstName +"' , '"+lastName+"' , '"+phoneNumber+ "', '"+ address +"', '"+dateOfBirth+"' );";
A better and safer option would be to use Parametrised query. Something like this.....
String connString = #"Data Source=C:\Users\User\documents\visual studio 2012\Projects\ADO_LINQ\ADO_LINQ\App_Data\MyDatabase.sdf;Persist Security Info = False";
using(SqlCeConnection myConnection = new SqlCeConnection(connString))
{
// Create the query
String myQuery = "INSERT INTO Player " +
" VALUES (#registrationID , #firstName , #lastName , #phoneNumber, #address , #dateOfBirth );";
//Initialuze the command
SqlCeCommand myCommand = new SqlCeCommand(myQuery, myConnection);
// Add parameters
myCommand.Parameters.AddWithValue("#registrationID" ,registrationID);
myCommand.Parameters.AddWithValue("#firstName" , firstName);
myCommand.Parameters.AddWithValue("#lastName" , lastName);
myCommand.Parameters.AddWithValue("#phoneNumber" , phoneNumber);
myCommand.Parameters.AddWithValue("#address" , address);
myCommand.Parameters.AddWithValue("#dateOfBirth" , dateOfBirth);
//Open Connection
myConnection.Open();
//Run the command
myCommand.ExecuteNonQuery();
}

error while executing a ms-access query

I created a query to insert into two ms access tables at a time in c#. I got the exception
{System.Data.OleDb.OleDbException: Characters found after end of SQL
statement. at
System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult
hr) at
System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS
dbParams, Object& executeResult) at
System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object&
executeResult) at
System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior
behavior, Object& executeResult) at
System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior
behavior, String method) at
System.Data.OleDb.OleDbCommand.ExecuteNonQuery() at
CompanyDetails.Model.CompanyDetailsModel.setCompanyDetailsToDB(CompanyDetailsDataList
_cmpDetailsList) in E:\Project\PBAttendence\ModifyPrivileage\CompanyDetails\Model\CompanyDetailsModel.cs:line
62}
my sample code is given below please solve my problem. sorry for my bad English.
int companyID = _cmpDetailsList[0].CompanyID;
string companyName = _cmpDetailsList[0].CompanyName;
string contactID = _cmpDetailsList[0].ContactID;
string companyAddress = _cmpDetailsList[0].CompanyAddress;
if (companyID == -1)
{
OleDbCommand cmd = new OleDbCommand("Insert into CompanyDetails([CompanyName],[CompanyAddress],[ContactID]) values ('" + companyName + "','" + companyAddress + "','" + contactID + "');Insert into UserCompanyDetails([UserID],[CompanyID]) values (" + "Select [UserID] from UserDetails;" + "," + "Select ##identity;" + "); ", conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
else
{
OleDbCommand upcmd = new OleDbCommand("update CompanyDetails set [CompanyName] = '" + companyName + "',[CompanyAddress] = '" + companyAddress + "',[ContactID] = '" + contactID + "' where [CompanyID] = #cmpID;", conn);
conn.Open();
upcmd.Parameters.AddWithValue("#cmpID", companyID);
upcmd.ExecuteNonQuery();
conn.Close();
}
now i split into two insert command but i got the error {System.Data.OleDb.OleDbException: Syntax error. in query expression 'Select [UserID] from UserDetails;
OleDbCommand cmd = new OleDbCommand("Insert into CompanyDetails([CompanyName],[CompanyAddress],[ContactID]) values ('" + companyName + "','" + companyAddress + "','" + contactID + "');", conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
OleDbCommand cmd1 = new OleDbCommand("Insert into UserCompanyDetails([UserID],[CompanyID]) values (" + "Select [UserID] from UserDetails;" + "," + "Select ##identity" + ");", conn);
conn.Open();
cmd1.ExecuteNonQuery();
conn.Close();
The problem is this line of code:
OleDbCommand cmd = new OleDbCommand("Insert into CompanyDetails([CompanyName],[CompanyAddress],[ContactID]) values ('" + companyName + "','" + companyAddress + "','" + contactID + "');Insert into UserCompanyDetails([UserID],[CompanyID]) values (" + "Select [UserID] from UserDetails;" + "," + "Select ##identity;" + "); ", conn);
You have two insert statements in the same OleDbCommand. Try to move this into two different steps:
Insert into CompanyDetails table
Insert into UserCompanyDetails table
Hope this helps you
First of all , it would have been easier with the raw sql command then your code generating the sql.
You might consider making a stored procedure since your command is getting kinda complex
If i'm correct , what you are currently trying to do is :
Insert into table1(x,y,z) values a,b,c;
Insert into table2(x,y) values select * from table3; , ##identity
The second sql command is invalid in both syntax and logic, your ##identity won't be static since you're inserting new records during your command.
My recommendation would be to do something like this :
Insert into table1(x,y,z) values a,b,c;
declare #table1Id int = ##identity
Insert into table2(x,y) select colA, #table1Id from table3;
You cannot have ; in queries in Access. See http://office.microsoft.com/en-us/access-help/HV080760224.aspx You will have to do the two inserts separately as suggested by #juanreyesv
You will have to do 3 queries,
Do the insert using your sql: "Insert into CompanyDetails([CompanyName],[CompanyAddress],[ContactID]) values ('" + companyName + "','" + companyAddress + "','" + contactID + "')
Get the ##identity using
Select ##identity and store it in a variable say idnt
Use the identity value obtained in 2. to do the third insert:
"Insert into UserCompanyDetails([UserID],[CompanyID])
Select UserID, " + idnt.ToString() + " from UserDetails"
Refer to http://msdn.microsoft.com/en-us/library/ks9f57t0%28VS.71%29.aspx

c# access database program

String strSql = "insert into BaseData (Item," + dataGridView1.Columns[3].Name + "," + dataGridView1.Columns[4].Name + ") values ('" + row.Cells[0].Value + "','" + row.Cells[3].Value + "','" + row.Cells[4].Value + "')";
objCmd = new OleDbCommand(strSql, lConn);
objCmd.ExecuteNonQuery();
strSql = "select id from BaseData where Item = '" + row.Cells[0].Value + "' and " + dataGridView1.Columns[1].Name + " = '" + row.Cells[3].Value + "' And " + dataGridView1.Columns[2].Name + " = '" + row.Cells[4].Value + "'";
OleDbCommand command = new OleDbCommand(strSql, lConn);
OleDbDataReader reader = command.ExecuteReader();
String id = "";
while (reader.Read())
{
id = reader.GetString(0);
}
reader.Close();
strSql = "insert into tranjaction (Base_id,quentity,price,other) values ('" + id + "' , ' " + row.Cells[2].Value + "','" + row.Cells[1].Value + "')";
objCmd = new OleDbCommand(strSql, lConn);
objCmd.ExecuteNonQuery();
When I run this, Microsoft Visual Studio Error occur on Line 10. (ExecuteReader)
The Error is here.
An unhandled exception of type 'System.Data.OleDb.OleDbException'
occurred in System.Data.dll
Additional information: No value given for one or more required
parameters.
How could I fix this error?.
Either your field names are wrong (quentity?) or it's because you have unbalanced fields to parameters. You are inserting into 4 fields, but you are only supplying 3 values. Use parameters instead, it would make your life easier.
Try changing it to this:
strSql = "insert into tranjaction (Base_id,quentity,price,other) values (#id , #quentity, #price, #other)";
using (OleDbCommand cmd = new OleDbCommand(sqlSql, IConn)) {
cmd.Parameters.AddWithValue("#id", id);
cmd.Parameters.AddWithValue("#quentity", row.Cells[2].Value);
cmd.Parameters.AddWithValue("#price", row.Cells[1].Value);
cmd.Parameters.AddWithValue("#other", other); // <- missing
cmd.ExecuteNonQuery();
}
When I've received this error in the past it has always been because of a simple typo. Like the others have mentioned it looks like you spelled "quantity" wrong which could be part of the problem.
In this line
strSql = "insert into tranjaction (Base_id,quentity,price,other) values ('" + id + "' , ' " + row.Cells[2].Value + "','" + row.Cells[1].Value + "')";
you are inserting 4 values (Base_id,quentity,price,other), but you are only inserting 3 values (id, row.Cells[2].Value, row.Cells[1].Value). Giving a value for other should fix the problem.
Another thing that would cause this error, which is probably your situation, is if you've spelled one of the column names incorrectly. And since you are using column names from your datagridview, and some of your written column names seem mis-spelled, you should double check the spelling in your query strings.

Categories

Resources