C# INSERT语句错误,未执行
试图从用户从文本框输入的数据中执行SQL语句,一旦用户单击按钮,它应该插入到表中,但表示insert语句中有错误 这是单击时的按钮代码:C# INSERT语句错误,未执行,c#,sql,sql-insert,C#,Sql,Sql Insert,试图从用户从文本框输入的数据中执行SQL语句,一旦用户单击按钮,它应该插入到表中,但表示insert语句中有错误 这是单击时的按钮代码: private void SaveBtn_Click(object sender, EventArgs e) { string Invoice = InvoiceNoTxt.Text; string Account = AccountTxt.Text; string dates = textBox1.T
private void SaveBtn_Click(object sender, EventArgs e)
{
string Invoice = InvoiceNoTxt.Text;
string Account = AccountTxt.Text;
string dates = textBox1.Text;
string TotalSells = TotalSellTxt.Text;
string Vats = VatTxt.Text;
string TotalCosts = TotalCostTxt.Text;
if (EditChoice == 1)
{
//this is the SQL statement that updates the table
Sql = String.Format("UPDATE InvoiceHeader " + "SET AccountCode = {0}," + "Day = '{1}'," + "TotalSell = {2}, " + "Vat = {3}, " + "TotalCost = {4}, " + "WHERE InvoiceNo = {5};", Account, dates, TotalSells, Vats, TotalCosts, Invoice);
}
else
{
//this is the SQL statement that adds to the table in the database
Sql = String.Format("INSERT INTO InvoiceHeader(AccountCode,Day,TotalSell,Vat,TotalCost) " + "VALUES " + "({0}," + "'{1}'," + "{2}," + "{3}," + "{4});", Account, dates, TotalSells, Vats, TotalCosts);
}
//this is calling the method that executes the SQL code
La(Sql);
//this reloads the data from the database with the new data in it
LoadData();
//this clears the data in the textfields and refreshs the panels to use again
Back();
}
这是执行sql的执行方法:
private void La(String Sql)
{
//this code in the method allows for the sql to execute from all the statements
DbConn = new OleDbConnection(ConString);
DbCmd = new OleDbCommand(Sql, DbConn);
DbConn.Open();
DbCmd.ExecuteNonQuery();
DbConn.Close();
}
它可能是查询文本中额外的逗号
"UPDATE InvoiceHeader " + "SET AccountCode = {0}," + "Day = '{1}'," + "TotalSell = {2}, " + "Vat = {3}, " + "TotalCost = {4}, " + "WHERE InvoiceNo = {5};"
如果查询文本位于多行上,则更容易识别
"UPDATE InvoiceHeader " +
"SET AccountCode = {0}," +
"Day = '{1}'," +
"TotalSell = {2}, " +
"Vat = {3}, " +
"TotalCost = {4}, " + // <-- here
"WHERE InvoiceNo = {5};"
“更新发票抬头”+
设置AccountCode={0}+
“Day='{1}',”+
“TotalSell={2},”+
“增值税={3},”+
“TotalCost={4},”+//单词“Day”可能是系统保留的单词,请尝试在其周围添加方括号,如下所示
Sql = String.Format("INSERT INTO InvoiceHeader(AccountCode,[Day],TotalSell,Vat,TotalCost) " + "VALUES " + "({0}," + "'{1}'," + "{2}," + "{3}," + "{4});", Account, dates, TotalSells, Vats, TotalCosts);
Sql = String.Format("UPDATE InvoiceHeader " + "SET AccountCode = {0}," + "[Day] = '{1}'," + "TotalSell = {2}, " + "Vat = {3}, " + "TotalCost = {4}, " + "WHERE InvoiceNo = {5};", Account, dates, TotalSells, Vats, TotalCosts, Invoice);
与您的错误无关,但您的代码易于SQL注入。您应该使用准备好的语句来解决这个问题。您能发布整个错误堆栈跟踪(例如异常.ToString()
)吗?感谢您尝试打开内部异常属性并查看它是否返回有关插入错误的有用信息?其次,您确定在*AccountCode,Day,TotalSell,Vat,TotalCost
)中没有输入错误吗。“TotalSell”中的附加“l”可能是问题所在。INSERT INTO语句中的System.Data.OleDb.OLEDBEException类型的未处理异常发生在System.Data.dll语法错误中。请确保在INSERT语句中正确写入列名。而且要小心,正如@Manfred Radlwimmer所说的,您的代码在尖叫着要SQL注入。