-6

please figure out the error in my code.it show syntax error INSERT INTO statement.

OleDbCommand cmd = new OleDbCommand("INSERT INTO tbbill(invoice,datetime,custm,total,tax,grand)VALUES(" + Convert.ToInt32(txtinvoice.Text) + ",'" + dateTimePicker1.Value.ToString("yyyy/MMM/dd") + "','" + Convert.ToString(txtcn.Text) + "','" + txtttl.Text + "','" + Convert.ToInt32(cmtax.Text) + "','" + txtgrdttl.Text + "')", con);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
con.Close();
Liam
  • 27,717
  • 28
  • 128
  • 190
Priyanka
  • 75
  • 1
  • 12

3 Answers3

4

It seems that you've commited all the sins possible in this short fragment. Something like that is expected:

// Make SQL readable
String sql =
  @"INSERT INTO tbbill(
      invoice,
      [datetime], /* reserved word */
      custm,
      total,
      tax,
      grand)
    VALUES(
      ?, ?, ?, ?, ?, ?)"; // Make SQL parametrized

// Put IDisposable into "using"
using (OleDbCommand cmd = new OleDbCommand(sql, con)) {
  // Parameterized 
  cmd.Parameters.Add(txtinvoice.Text);
  cmd.Parameters.Add(dateTimePicker1.Value);
  cmd.Parameters.Add(txtcn.Text);
  cmd.Parameters.Add(txtttl.Text);
  cmd.Parameters.Add(cmtax.Text);
  cmd.Parameters.Add(txtgrdttl.Text);

  cmd.ExecuteNonQuery();
}

// Do not close that's not opened by you (i.e. con)
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
2

Apart from your weird INSERT statement, your column name datetime is a reserve word in Access. You should escape it suing [] like below.

INSERT INTO tbbill(invoice,[datetime],custm,total,tax,grand) 

Your current query is open to SQL Injection and so as suggested in comment consider using parameterized query instead.

Rahul
  • 76,197
  • 13
  • 71
  • 125
0

This should work:

OleDbCommand cmd = new OleDbCommand(@"INSERT INTO tbbill(invoice,[datetime],custm,total,tax,grand) 
VALUES(" + Convert.ToInt32(txtinvoice.Text) + ",\"" +          
dateTimePicker1.Value.ToString("yyyy/MMM/dd") + "\",\"" + 
Convert.ToString(txtcn.Text) + "\",\"" + txtttl.Text + "\",\"" + 
Convert.ToInt32(cmtax.Text) + "\",\"" + txtgrdttl.Text + "\")", con);
cmd.CommandType = CommandType.Text; 
cmd.ExecuteNonQuery(); 
con.Close();

EDIT:

As stated by others, your query is still open to SQL injection. Dmitry's answer will be the safest and efficient option.

Chawin
  • 1,438
  • 1
  • 21
  • 33