Ram
Ram

Reputation: 11

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...

Upvotes: 1

Views: 65

Answers (3)

Ram
Ram

Reputation: 11

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

Thanks Ram

Upvotes: 0

Soner Gönül
Soner Gönül

Reputation: 98858

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.

Upvotes: 2

Giorgi
Giorgi

Reputation: 30883

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

Upvotes: 0

Related Questions