problem inserting data into database using sql command - c#

I have received the following error:
Syntax error in INSERT INTO statement.
I don't seem to be able to find the mistake. here is the code:
if (Request["su"] == "save")
{
string sqlCommand = "";
string fileName = "UsersDB.accdb";
string tableName = "Table 2";
string website_name, website_psw;
website_name = Request["psw_name"];
website_psw = Request["psw"];
sqlCommand = "INSERT INTO " + tableName + " (fname, lname, umail, upassword, gender, age, uid) ";
sqlCommand += "VALUES ('"+0+ "','" + Session["umail"].ToString() + "','" + website_psw + "','" + website_name + "')";
MyAdoHelper.DoQuery(fileName, sqlCommand);
}
As for the database, it has 4 rows:
uid, uidd, psw_name, psw
What is the issue in the code which leads to such error?

It looks like your INSERT statement is specifying 7 columns (fname, lname, umail, upassword, gender, age, uid) to insert into and only 4 columns of data.
The table name with a space in it is also likely to cause an issue. Enclosing it in square brackets should fix that issue.
You SQL should start like this (if this text: " it has 4 rows: uid, uidd, psw_name, psw" means your table has 4 columns):
INSERT INTO [Table 2] (uid, uidd, psw_name, psw) VALUES (...

Try this two lines :
sqlCommand = "INSERT INTO " + tableName + " (fname, lname, umail, upassword, gender,
age, uid) ";
sqlCommand += "VALUES (\'"+0+ "\',\'" + Session["umail"].ToString() + "\',\'" +
website_psw + "\',\'" + website_name + "\')";

Related

C# SQL insert query syntax error with MS Access

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]) .."

Error: There are more columns in the INSERT statement than values specified in the VALUES clause

I've checked my values but it still says that I do not have enough. I have one value that isn't in the insert-statement but it's an identity-value, so I guess I don't have to specify that in my code?!?!
Anyway here's the code:
string Fname = tbFIRSTNAME.Text.Trim();
string Lname = tbLASTNAME.Text.Trim();
string Sname = tbStreetName.Text.Trim();
string SSN = tbSSN.Text.Trim();
string CrimeID = cmbCRIMEID.Text.ToString();
string DangerLVL = cmbDANGERLEVEL.Text.ToString();
string CrimeDesc = rtbCrimeInfo.Text.Trim();
string str = "insert into Crooks (FirstName, LastName, StreetName, SSN, CrimeID, DangerLevel, CrimeDescription) values ('" + Fname + '"' + Lname + '"' + Sname + '"' + SSN + '"' + DangerLVL + '"' + CrimeID + '"' + CrimeDesc + "')";
clsDB.InsUpDel(str);
Your basic error, as others stated, is that you are not separating all the values with commas.
Apart from that, you have a big security flaw. And that is to use your values directly from your textboxes. That is the most insecure and most common security flaw in software design and will potentially lead you to have SQL Injection attacks to your application. To avoid that, you should use parametrized query. This is a resumed code, but you should so something like this:
using(MySqlConnection conn = new MySqlConnection("YourConnectionString"))
{
conn.Open();
MySqlCommand command = conn.CreateCommand();
command.CommandText = "insert into Crooks (FirstName, LastName, StreetName, SSN, CrimeID, DangerLevel, CrimeDescription) VALUES (#FirstName, #LastName, #StreetName, #SSN, #CrimeID, #DangerLevel, #CrimeDescription)";
command.Parameters.AddWithValue("#FirstName", tbLASTNAME.Text.Trim());
command.Parameters.AddWithValue("#LastName", tbStreetName.Text.Trim());
/*
...
AND SO ON WITH OTHER PARAMETERS
...
*/
command.ExecuteNonQuery();
conn.Close();
}
The problem is that you haven't set comma between your values (So you are actually entering one value not 7):
string str = "insert into Crooks (FirstName, LastName, StreetName, SSN, CrimeID, DangerLevel, CrimeDescription) values ('" + Fname + "','" + Lname + "','" + Sname + "'," + SSN + "," + DangerLVL + "," + CrimeID + ",'" + CrimeDesc + "')";
Clearly some of varchar types are not enclosed between '' too. this is not the case right now, but after adding commas you may get other errors because of type mismatches

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# syntax error in INSERT INTO statement

I'm having the error at the line: ins.ExecuteNonQuery().ToString(); OledDbException was unhandled Syntax error in INSERT INTO statement.
How do I fix this?
string strOleDbConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Project.mdb";
OleDbConnection objConnection = new OleDbConnection(strOleDbConnectionString);
string newTagID = textBox1.Text;
string newUser = textBox2.Text;
string newAge = textBox3.Text;
string newPhoneNumber = textBox4.Text;
string insertString = "INSERT INTO jiahe ([Tag ID], User, Age, [Phone Number]) VALUES ('" + newTagID + "', '" + newUser + "', '" + newAge + "', '" + newPhoneNumber + "')";
OleDbCommand ins = new OleDbCommand(insertString, objConnection);
ins.Connection.Open();
ins.ExecuteNonQuery().ToString();
ins.Connection.Close();
Your problem is probably one these three:
Outright syntax error not clearly visible with the hideous unparametrized SQL statement :p
newUser or some other field has a ' somewhere and is screwing up the syntax.
You are trying to insert a numeric value (Age?) as a string.
You should easily solve the first two creating a breakpoint after the insertString statement construction and checking out what the string really contains. The third one is even easier to check, just review the data types of the table's fields in your data base.
Notwithstanding, you should change the use of your command to use parameters and not build the query string with string concatenation (which is susceptible to sql injection attacks).
The issue is most likely because [Tag ID], User, Age, [Phone Number] are not all strings. In your SQL, any non-string column data should not be wrapped by quotes (').
To fix the immediate problem (assuming [Tag ID] is an integer):
string insertString = "INSERT INTO jiahe ([Tag ID], User, Age, [Phone Number]) VALUES (" + newTagID + ", '" + newUser + "', '" + newAge + "', '" + newPhoneNumber + "')";
However, you should structure your code to avoid sql injection, have cleaner code, and also not worry about the quotes:
string insertString = "INSERT INTO jiahe ([Tag ID], User, Age, [Phone Number]) VALUES (#TagID, #User, #Age, #PhoneNumber)";
OleDbCommand ins = new OleDbCommand(insertString, objConnection);
ins.Parameters.Add(new OleDbParameter("#TagID",newTagID);
ins.Parameters.Add(new OleDbParameter("#User",newUser);
ins.Parameters.Add(new OleDbParameter("#Age",newAge);
ins.Parameters.Add(new OleDbParameter("#PhoneNumber",newPhoneNumber);
ins.Connection.Open();
ins.ExecuteNonQuery();
ins.Connection.Close();

insert into database

I've made sure everything pertains to the column types in the database, but I keep getting an SQLCeException. Can anyone tell me what's wrong with this code?
private void ANDPaddDriverButton_Click(object sender, EventArgs e)
{
string first = ANDPfirstNametextBox.Text;
string last = ANDPlastNametextBox.Text;
string mid = textBox5.Text;
string phone = ANDPphonetextBox.Text;
string social = ANDPsSNtextBox.Text;
// EmployeeType="Employee"
string city = ANDPCityTextbox.Text;
string state = ANDPStatetextBox.Text;
string zip = ANDPzipCodetextbox.Text;
string email = ANDPemailtextBox.Text;
string address = ANDPaddressTextBox.Text;
string user = userName.Text;
DBConn.Open();
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO [Employee Table] VALUES (" +
first + "," + last + "," + mid + "," + address + "," + phone + "," + social + ","
+ "Employee" + "," + city + "," + state + "," + zip + "," + email + "," + userName + ")", DBConn);
cmd.ExecuteNonQuery();
DBConn.Close();
}
Use Parameters to prevent SQL injection, and the Columns names, because you are relying in the quantity, and order of your table's columns and it will likely change in the future (I'm guessing the column names):
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO [Employee Table] (First, Last, Mid, Address, Phone, Social, Employee, City, State, Zip, Email, UserName) VALUES (#First, #Last, #Mid, #Address, #Phone, #Social, #Employee, #City, #State, #Zip, #Email, #UserName)", DBConn);
cmd.Parameters.AddWithValue("#First", first);
cmd.Parameters.AddWithValue("#Last", last);
cmd.Parameters.AddWithValue("#Mid", mid);
cmd.Parameters.AddWithValue("#Address", address);
cmd.Parameters.AddWithValue("#Phone", phone);
// etc. each column
By the way try to not use spaces in table and columns names ;-)
Your fields of type string/varchar shall be enclosed in single quotes!
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO [Employee Table] VALUES (" +
"'" + first + "',"
and so on...
Also, as somebody else already commented you're going to greatly expose your code to SQL injection attacks
As Lorenzo said, the string values must be enclosed with single quotes, but please read this page which explains why you shouldn't build a query this way, and shows you how to do it with parameters.

Categories

Resources