在c#中插入INTO语法错误

时间:2015-10-08 08:43:42

标签: c# sql ms-access-2003

请弄清楚我的code.it中的错误显示语法错误INSERT INTO语句。

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();

3 个答案:

答案 0 :(得分:4)

似乎你已经在这个短片段中提交了所有可能的罪。 这样的事情是预期的:

// 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)

答案 1 :(得分:2)

除了您奇怪的INSERT语句外,您的列名datetime在Access中为reserve word。你应该像以下一样逃避[]

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

您当前的查询对SQL注入是开放的,因此在评论中建议考虑使用参数化查询。

答案 2 :(得分:0)

这应该有效:

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();

修改

正如其他人所说,您的查询仍然对SQL注入开放。德米特里的答案将是最安全和最有效的选择。