[英]INSERT INTO syntax error in c#
please figure out the error in my code.it show syntax error INSERT INTO statement.请找出我的代码中的错误。它显示语法错误 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();
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)
Apart from your weird INSERT
statement, your column name datetime
is a reserve word in Access.除了奇怪的
INSERT
语句之外,您的列名datetime
是 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.您当前的查询对 SQL 注入开放,因此根据评论中的建议,请考虑改用参数化查询。
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.正如其他人所说,您的查询仍然对 SQL 注入开放。 Dmitry's answer will be the safest and efficient option.
德米特里的答案将是最安全有效的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.