尝试将新记录添加到数据库。我在不同的项目上尝试过这种类型的代码并且工作正常。
我在INSERT语句中不断收到语法错误:
我似乎无法找到问题所在。我已经搜索了其他无法解决的解决方案。我现在已经检查了几次表名,我看不出任何不一致的地方。
请注意,我确实有其他所有剩余的代码来添加记录,但这里没有包含它。
任何帮助都会很棒。如果有人需要更多信息,我很乐意遵守。
我正在使用C#并使用Access数据库。
void addRecord()
{
OleDbConnection myDatabaseConnection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;" + @"Data Source=..\..\Database\TestionRetail.accdb;");
System.Data.OleDb.OleDbCommand command = new OleDbCommand();
command.Connection = myDatabaseConnection;
myDatabaseConnection.Open();
command.CommandText = "INSERT INTO Employee (PayrollNo, Title, FirstName, Surname, Position, DOB, Email, PhoneNumber, AlternateNumber, AddressLine1, AddressLine2, City, Postcode, ContractType)" +
"VALUES (@PayrollNo, @Title, @FirstName, @Surname, @Position, @DOB, @Email, @PhoneNumber, @AlternateNumber, @AddressLine1, @AddressLine2, @City, @Postcode, @ContractType)";
command.Parameters.AddWithValue("@PayrollNo", txtPayroll.Text);
command.Parameters.AddWithValue("@Title", cmbTitle.SelectedIndex.ToString());
command.Parameters.AddWithValue("@FirstName", txtFirstName.Text);
command.Parameters.AddWithValue("@Surname", txtSurname.Text);
command.Parameters.AddWithValue("@Position", txtPosition.Text);
command.Parameters.AddWithValue("@DOB", dtpDOB.Value.ToShortDateString());
command.Parameters.AddWithValue("@Email", txtEmail.Text);
command.Parameters.AddWithValue("@PhoneNumber", txtPhoneNo.Text);
command.Parameters.AddWithValue("@AlternateNumber", txtAltPhoneNo.Text);
command.Parameters.AddWithValue("@AddressLine1", txtAddress1.Text);
command.Parameters.AddWithValue("@AddressLine2", txtAddress2.Text);
command.Parameters.AddWithValue("@City", txtTown.Text);
command.Parameters.AddWithValue("@Postcode", mtbPostcode.Text);
command.Parameters.AddWithValue("@ContractType", cmbContract.SelectedIndex.ToString());
try
{
command.ExecuteNonQuery();
var item = new NotifyIcon(this.components);
item.Visible = true;
item.Icon = System.Drawing.SystemIcons.Information;
item.ShowBalloonTip(2000, "Record Added", "Successfully added new record", ToolTipIcon.Info);
this.Hide();
}
catch (Exception exp)
{
MessageBox.Show(exp.ToString());
}
//5. Close the database
myDatabaseConnection.Close();
this.Hide();
}
答案 0 :(得分:1)
感谢大家的帮助,我通过在
中加上方括号来解决问题答案 1 :(得分:0)
我相信在下一行的右括号后需要一个空格:
command.CommandText = "INSERT INTO Employee (PayrollNo, Title, FirstName, Surname, Position, DOB, Email, PhoneNumber, AlternateNumber, AddressLine1, AddressLine2, City, Postcode, ContractType)" +
否则您的查询将显示为:
INSERT INTO Employee (PayrollNo, Title, FirstName, Surname, Position, DOB, Email, PhoneNumber, AlternateNumber, AddressLine1, AddressLine2, City, Postcode, ContractType)VALUES (@PayrollNo, @Title, @FirstName, @Surname, @Position, @DOB, @Email, @PhoneNumber, @AlternateNumber, @AddressLine1, @AddressLine2, @City, @Postcode, @ContractType)
这就是INSERT
之后的原因,因为它是在遇到语法错误之前识别的第一个/最后一个关键字。
答案 2 :(得分:0)
日期字段不是文字。因此:
command.Parameters.AddWithValue("@DOB", dtpDOB.Value);