Syntax error in UPDATE statement OleDb Exception - c#

I check my SQL Statement many times and it seems that my SQL Statement is Error. I don't why it doesn't work. My SQL Statement is correct and It resulted to this OleDBException "Syntax error in UPDATE statement.".
Here is the code
OleDbConnection CN = new OleDbConnection(mysql.CON.ConnectionString);
CN.Open();
cmd1 = new OleDbCommand("Update Mosque Set Name='" + txtNAME.Text + "', No='" + Convert.ToInt32(txtNO.Text) + "', place='" + txtPlace.Text + "', group='" + txtGroup.Text + "', description='" + txtdec.Text + "' where id='" + txtID.Text + "'", CN);
cmd1.ExecuteNonQuery();
CN.Close();
need help please to know what is the error here

I don't know what database are you using, but I am sure that GROUP is a reserved keyword in practically any existant SQL database. This word cannot be used without some kind of delimiter around it. The exact kind of delimiter depend on the database kind. What database are you using?
Said that, please do not use string concatenation to build sql commands, but use always a parameterized query. This will allow you to remove any possibilities of Sql Injection and avoid any syntax error if one or more of your input string contains a single quote somewhere
So, supposing you are using a MS Access Database (In Access also the word NO is a reserved keyword and the delimiters for reserved keywords are the square brakets) you could write something like this
string commandText = "Update Mosque Set Name=?, [No]=?, place=?, " +
"[Group]=?, description=? where id=?"
using(OleDbConnection CN = new OleDbConnection(mysql.CON.ConnectionString))
using(OleDbCommand cmd1 = new OleDbCommand(commandText, CN))
{
CN.Open();
cmd1.Parameters.AddWithValue("#p1",txtNAME.Text);
cmd1.Parameters.AddWithValue("#p2",Convert.ToInt32(txtNO.Text));
cmd1.Parameters.AddWithValue("#p3",txtPlace.Text);
cmd1.Parameters.AddWithValue("#p4",txtGroup.Text);
cmd1.Parameters.AddWithValue("#p5",txtdec.Text);
cmd1.Parameters.AddWithValue("#p6",txtID.Text);
cmd1.ExecuteNonQuery();
}
Instead for MySQL you have to use the backticks around the GROUP keyword
string commandText = "Update Mosque Set Name=?, No=?, place=?, " +
"`Group`=?, description=? where id=?"

Hard to tell without knowing the values of the texboxes, but I suspect that one of them has an apostrophe which is causing an invalid syntax.
I recommend using parameters instead:
cmd1 = new OleDbCommand("Update Mosque Set [Name]=#Name, [No]=#No, [place]=#Place, [group]=#Group, [description]=#Description WHERE id=#ID", CN);
cmd1.Parameters.AddWithValue("#Name",txtNAME.Text);
cmd1.Parameters.AddWithValue("#No",Convert.ToInt32(txtNO.Text));
// etc.

Related

Insert comma into MS Access database using Visual Studio [duplicate]

This question already has answers here:
Single quote handling in a SQL string
(3 answers)
Closed 6 months ago.
I'm creating an application using Visual Studio 2019, with a connection to an MS Accsess database to add, get, modify and delete values inside the database.
I'm willing to insert a text that could contain a comma, for example : Gousse d'ail. But I know there will be a problem because the string has to be surrounded by commas. So I added a backslash before every extra comma inside the text I'm willing to insert.
The thing is a get an error message saying there is a syntax error, I believe it's because of the backslash.
Here is the message I get :
System.Data.OleDb.OleDbException (0x80040E14) : Syntax error (missing operator) in query expression " 'Gousse d\'ail', unite = 'kg', allergene = False, fournisseurID = 1 WHERE ingrédientID = 40; "
Everything works really well until there is comma.
Here is the method I use to insert into the database:
public void UpdateIngédient(int ingredientID, InfoIngredient ing)
{
string query = "UPDATE Ingrédients ";
query += "SET nom = '" + ing.Nom + "', unite = '" + ing.Unité + "', allergene = " + ing.Allergene + ", fournisseurID = " + ing.Fournisseur;
query += " WHERE ingredientID = " + ingredientID + ";";
OleDbCommand com = new OleDbCommand(query, oleConnection);
com.ExecuteNonQuery();
}
Your query is begging for SQL injection, as well as bugs exactly like the one you've encountered.
If you're doing any work with a SQL table (or OLE in your case) I strongly recommend spending some time to look into SQL injection to understand the risks.
It's very easy to defend against SQL injection and a rewrite of your code is shown below to protect against it.
void UpdateIngédient(int ingredientID, InfoIngredient ing)
{
string query = "UPDATE Ingrédients SET nom = #nom, unite = #unite, allergene = #allergene, fournisseurID = #fournisseur WHERE ingredientID = #ingredientID;";
OleDbCommand cmd = new OleDbCommand(query, oleConnection);
cmd.Parameters.Add(new OleDbParameter("#nom", ing.Nom));
cmd.Parameters.Add(new OleDbParameter("#unite", ing.Unité));
cmd.Parameters.Add(new OleDbParameter("#allergene", ing.Allergene));
cmd.Parameters.Add(new OleDbParameter("#fournisseur", ing.Fournisseur));
cmd.Parameters.Add(new OleDbParameter("#ingredientID", ingredientID));
OleDbCommand com = new OleDbCommand(query, oleConnection);
com.ExecuteNonQuery();
}
This should safeguard against "unexpected" characters in your strings such as the ' character

execute sql command in asp.net

I have a problem with executing a sql command to the DB. The command should add a new user to the 'users' table.
But when I run the code, I get this Exception on:
command.ExecuteNonQuery();
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.OleDb.OleDbException: Syntax error in INSERT INTO statement.
this is the code of the page - GetSignIn.cshtml :
#{
string Uname = Request["name"];
string userName = Request["userName"];
string pass = Request["passWord"];
string pic = Request["pic"];
string privacy = Request["privacy"];
if(pic == null)
{
pic = "Shared/defaultPic.jpg";
}
System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Etay\Documents\Visual Studio 2012\WebSites\Josef\Shared\users.mdb";
try
{
System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand();
command.Connection = connection;
connection.Open();
command.CommandText = "INSERT INTO users (userName,passWord,Uname,pic) VALUES ('" + userName + "', '" + pass + "', '" + Uname + "', '" + pass + "', " + pic + ")";
command.ExecuteNonQuery();
Response.Redirect("../HtmlPage.html");
}
finally
{
connection.Close();
}
}
What should I change in my code? Why is it happening? Where is the syntax error in the INSERT INTO?
Use parameterized queries. Here is your statement rewritten to make use of them.
I replaced your try/finally with a using block although your try/finally was acceptable.
Parameterized queries prevent errors and Sql Injection Attacks. An error could occur in your existing code if I were to submit a tick as a part of my user name or password. In the current form this would result in an exception. This is because the tick character is used to quote strings in sql syntax.
using (System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection())
{
connection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Etay\Documents\Visual Studio 2012\WebSites\Josef\Shared\users.mdb";
using (System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand())
{
command.Connection = connection;
command.CommandText = "INSERT INTO users (userName,passWord,Uname,pic) VALUES (?,?,?,?)";
command.Parameters.Add(userName);
command.Parameters.Add(pass);
command.Parameters.Add(Uname);
command.Parameters.Add(pic);
connection.Open();
command.ExecuteNonQuery();
}
}
About parameters for an OleDb connection from OleDbCommand.Parameters
Remarks
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used. For example:
SELECT * FROM Customers WHERE CustomerID = ?
Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.
What should I change in my code?
Change to parameters (that also fixes the problem that you don;t have quotes around the pic value)
Remove the second instance of pass in your values
command.CommandText = "INSERT INTO users (userName,passWord,Uname,pic) VALUES (#userName, #pass, #Uname, #pic)";
command.Parameters.Add("#userName").Value = userName;
.. etc.
It's unclear what the type if pic is - you are passing a string but I can;t tell of the column stores a file path or if you are indending to serialize the file and store it in a pinary field.
You set 4 fields after the "INTO" clause, however you're passing 5 parameters:
"INSERT INTO users (userName,passWord,Uname,pic) VALUES ('" + userName + "', '" + pass + "', '" + Uname + "', '" + pass + "', " + pic + ")";
Just add the fifth field, or remove one parameter from the VALUES part
Please check take a look at your Insert statement, it looks like that you provided password value twice.
The number of query values and the destination fields should be same in an INSERT statement.
You have the wrong number parameters in your insert statement. For clarity, why not use string.Format to keep everything uniform? (Assuming these are all string types)
var rawSql = #"Insert INTO Users (userName,passWord,Uname,pic) VALUES ('{0}','{1}','{2}','{3}')";
command.CommandText = string.Format(rawSql, userName, pass, Uname, pic);
command.ExecuteNonQuery();
However, it also looks like you probably want to include that 5th parameter as well - just extend the format :
var rawSql = #"Insert INTO Users (userName,passWord,Uname,pic, privacy) VALUES ('{0}','{1}','{2}','{3}','{4}')";
command.CommandText = string.Format(rawSql, userName, pass, Uname, pic, privacy);
command.ExecuteNonQuery();
Since most of the answers failed to address the SQL Injection vulnerability, here's an example with parameterized queries. In addition to preventing SQL Injection attacks, it also makes it easier to troubleshoot these types of issues, and you don't need to worry about quoting or not quoting parameters.
System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Etay\Documents\Visual Studio 2012\WebSites\Josef\Shared\users.mdb";
try
{
System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand();
command.Connection = connection;
connection.Open();
command.CommandText = "INSERT INTO users (userName, passWord, Uname, pic, privacy) VALUES (?, ?, ?, ?, ?)";
command.Parameters.Add(userName);
command.Parameters.Add(pass);
command.Parameters.Add(name);
command.Parameters.Add(pic);
command.Parameters.Add(privacy);
command.ExecuteNonQuery();
Response.Redirect("../HtmlPage.html");
}
finally
{
connection.Close();
}
Tnx 4 the help
It happend to be a problem with the database - you can not apply a INSERT INTO statement where the column name is "password". "password" is a Reserved word
in SQL.
Tnx again,
Etay

Can't delete row from single column table

I have problem with the query to delete a row from table(I am using MySQL lite), I'm using data bound comobox to select what to delete but I get this error {"Invalid column name 'Football'."} on executing the command
con.Open();
SqlCommand cm = new SqlCommand("DELETE FROM Sports WHERE Sport = " + cbSelectSport.Text + "", con);
cm.ExecuteNonQuery();
MessageBox.Show("Done");
con.Close();
String concatenation should be avoided in almost every case. You should use parameterized queries whenever possible. You avoid conversions, SQL injection attacks and the code is typically faster because the server can reuse execution plans
Writing a parameterized query is also easier:
using(var con=new SqlConnection(...))
{
con.Open();
var cm = new SqlCommand("DELETE FROM Sports WHERE Sport = #sports", con);
var parameter=cm.Parameters.AddWithValue("#sports",cbSelectSport.Text);
cm.ExecuteNonQuery();
MessageBox.Show("Done");
};
This way the parameter values are passed out of band (ie outside the query) without converting to text. This is extremely useful when you want to pass decimal or date values.
Most people would warn against using AddWithValue because it makes too many assumptions based on its input value that can hurt performance. In this case you can use Add to create the parameter, then set its value, size, precision etc:
var parameter=cm.Parameters.Add("#sports",SqlDbType.NVarChar);
parameter.Size=20;
parameter.Value=cbSelectSport.Text;
Be careful with you syntax.
I don't know the type of the sport column, but I think need to enclose your value in quotes( single or double).
new SqlCommand("DELETE FROM Sports WHERE Sport = \"" + cbSelectSport.Text + "\", con);
or
new SqlCommand("DELETE FROM Sports WHERE Sport = '" + cbSelectSport.Text + "', con);
You must specify textvalue in single quotation marks ''.
SqlCommand cm = new SqlCommand("DELETE FROM Sports WHERE Sport = '" + cbSelectSport.Text + "'", con);
You might want to add the single quote:
SqlCommand cm = new SqlCommand("DELETE FROM Sports WHERE Sport = '" + cbSelectSport.Text + "'", con);
You should use parametrized query to prevent SQL Injection attack. Also it will solve your problem. By the way you can just add single quotes to your query.
"DELETE FROM Sports WHERE Sport = '" + cbSelectSport.Text + "'"

missing semicolon (;) at the end of sql statement

im using access database and im getting this weird error...
missing semicolon at the end of sql statement...
p.s i try to put the semicolon but again same thing...error again...
please help.
this is the code and the error start at Insert Into Statement :
oleDbConnection1.Open();
Int32 sasia_aktuale;
Int32 sasia_e_shtuar = Convert.ToInt32(textBox1.Text.Trim());
string kerkesa = "select * from magazina where emri = '"+listBox1.SelectedItem+"'";
OleDbCommand komanda = new OleDbCommand(kerkesa, oleDbConnection1);
OleDbDataReader lexo = komanda.ExecuteReader();
lexo.Read();
sasia_aktuale = Convert.ToInt32(lexo.GetValue(2).ToString());
lexo.Close();
Int32 sasia_totale = sasia_aktuale + sasia_e_shtuar;
oleDbDataAdapter1.InsertCommand.CommandText =
"insert into magazina(sasia) values('" + sasia_totale + "') where emri= '" + listBox1.SelectedItem + "'";
oleDbDataAdapter1.InsertCommand.ExecuteNonQuery();
MessageBox.Show("Sasia per produktin " + listBox1.SelectedItem + " u shtua me sukses!", "Sasia u shtua");
oleDbConnection1.Close();
You are mixing a WHERE clause with an INSERT statement, the two do not go together:
oleDbDataAdapter1.InsertCommand.CommandText =
"insert into magazina(sasia) values('" + sasia_totale + "')";
Do you mean an UPDATE statement?
I'd also advise you to look up SQL injecton, and using SqlParameters to build your queries. Your code, currently is very insecure.
I can see you are after an UPDATE command. The INSERT SQL command is just going to insert whatever you give it. An example of an UPDATE command, using SqlParameters to help avoid SQL injection, is below, although this is untested as I obviously don't have access to your setup (nor am I doing this with an IDE):
var updateCommand = new OleDbCommand("UPDATE magazina SET sasia = #sasia_totale WHERE emri = #emri");
updateCommand.Parameters.AddWithValue("#sasia_totale", sasia_totale);
updateCommand.Parameters.AddWithValue("#emri", listBox1.SelectedItem.ToString());
oleDbDataAdapter1.UpdateCommand = updateCommand;
oleDbDataAdapter1.UpdateCommand.ExecuteNonQuery();

SQLite not inserting into

I have the following code block
SQLiteConnection cnn = new SQLiteConnection("Data Source=" + getDBPath());
cnn.Open();
SQLiteCommand mycommand = new SQLiteCommand(cnn);
string values = "'" + this.section + "','" + this.exception + "','" + this.dateTimeString + "'";
string sql = #"INSERT INTO Emails_Pending (Section,Message,Date_Time) values (" + values + ")";
mycommand.CommandText = sql;
mycommand.ExecuteNonQuery();
cnn.Close();
When I execute it , nothing happens, no errors are produced, but nothing gets inserted, what am I doing wrong?
Path to DB is correct!
Insert statement works, tried it in a SQLLite GUI (no problems there)
Here is the SQL Snippet:
"INSERT INTO Emails_Pending (Section,Message,Date_Time) values ('Downloading Received Messages','Object reference not set to an instance of an object.','04.12.2009 11:09:49');"
How about adding Commit before Close
mycommand.Transaction.Commit();
You should always use transactions and parameterized statements when using sqlite, else the performance will be very slow.
Read here: Improve INSERT-per-second performance of SQLite?
Your approach is vulnerable to sql injection too. A message in an email can have a piece of sql in its body and your code will execute this piece of sql. You can also run into problems when the message in your string values contains a " or a ' .

Categories

Resources