简体   繁体   中英

C#.net - MS Access - insert into statement giving error “Syntax Error”,

insertBankMas = ""; 
insertBankMas = "INSERT INTO IntNotes (Room,Size) VALUES('" + txtRoom.Text + "','" + txtSize.Text + "')";    
PbdataAdapter = new OleDbDataAdapter(insertBankMas, PbSQLConnection);
openconnection();

insertcommand.ExecuteNonQuery();
MessageBox.Show("Room is Added");

Please correct me...

SIZE is a reserved keyword for Microsoft OleDb provider. You need to use it with square brackets like [SIZE] . As a best practice, change it to non -reserved word. And since your sql is an INSERT query, you don't need OleDbDataAdapter . This structure will use when you get data from your database. Just use ExecuteNonQuery to execute your insert query.

Bur more important

You should always use parameterized queries . This kind of string concatenations are open for SQL Injection attacks.

Also use using statement to dispose your OleDbConnection and OleDbCommand automatically instead of calling Close or Dispose methods manually.

using(var connection = new OleDbConnection(conString))
using(var cmd = connection.CreateCommand())
{
    cmd.CommandText = "INSERT INTO IntNotes (Room, [Size]) VALUES(?, ?)";
    cmd.Parameters.Add("?", OleDbType.VarWChar).Value = txtRoom.Text;
    cmd.Parameters.Add("?", OleDbType.VarWChar).Value = txtSize.Text;
    // I assume your column types mapped with VarWChar

    connection.Open();
    int effectedRows = cmd.ExecuteNonQuery();
    if(effectedRows > 0)
    {
       MessageBox.Show("Room is Added");
    }   
}

By the way, I strongly suspect your Size column should(?) be some numeric value based on it's name. You might wanna change it's column type instead.

The error is probably happening because the data that you enter in textboxes contains special characters that need to be escaped. Even if the data does not need to be escaped you must not build sql commands using string concatenation because that can cause sql injection attacks. Instead you should use parameterized statements and pass the user data as parameters.

See this article for more details: SQL Injection Attacks and Some Tips on How to Prevent Them

My Sincere thanks to everyone, reminded me SIZE is a keyword. Its WORKING, When I changed the SIZE field name to ROOMSIZE

Thanks Ram

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM