Trying to execute a SQL statement from data that is being input by the user from textboxes and once they click a button it should insert into the table, but is saying i have an error in the INSERT statement
This is the Button code when clicked:
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();
}
this is the execute method to execute the 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();
}
It's probably the extra comma in your query text.
"UPDATE InvoiceHeader " + "SET AccountCode = {0}," + "Day = '{1}'," + "TotalSell = {2}, " + "Vat = {3}, " + "TotalCost = {4}, " + "WHERE InvoiceNo = {5};"
It's easier to spot if you have your query text on multiple lines.
"UPDATE InvoiceHeader " +
"SET AccountCode = {0}," +
"Day = '{1}'," +
"TotalSell = {2}, " +
"Vat = {3}, " +
"TotalCost = {4}, " + // <-- here
"WHERE InvoiceNo = {5};"
The word 'Day' could be a system reserved word, try adding square brackets around it like such...
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.