Reputation: 1
I am beginners I am using inserting data from datetimepicker to ms access. My code is:
private void SaveSale()
{
string connString = ConfigurationManager.ConnectionStrings["saledbx"].ConnectionString;
string cmdString = "INSERT INTO Sale (Date, Sale, Expense) VALUES (@Date, @Sale, @Expense)";
using(OleDbConnection con = new OleDbConnection(connString))
{
using(OleDbCommand cmd = new OleDbCommand(cmdString, con))
{
con.Open();
cmd.Parameters.AddWithValue("@Date", TodayDatePicker.Text);
cmd.Parameters.AddWithValue("@Sale", SaleTextBox.Text);
cmd.Parameters.AddWithValue("@Expense", ExpenseTextBox.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Today Sale is added Successfully!", "Sale Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
I am facing this error:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Syntax error in INSERT INTO statement.
Upvotes: 0
Views: 819
Reputation: 216253
Date is a reserved keyword. If you can't change that field's name, then you should enclose it between square brackets
string cmdString = "INSERT INTO Sale ([Date], Sale, Expense) VALUES (@Date, @Sale, @Expense)";
Next, I suggest to use Add instead of AddWithValue in particular because you are working with dates that are prone to many conversion errors.
cmd.Parameters.Add("@Date", OleDbType.Date).Value = TodayDatePicker.Value;
In this way you can tell your database engine the exact datatype of the parameter passed and avoid any conversion from string to datetime values
Upvotes: 2