我有一个带有表(DV1)的Access DB,其中包含[ID TIME CODE REASON]列。我只是想更新表格。我一直收到INSERT INTO sytax错误。我看到的一切看起来都很好。我已经尝试了一切。 我打开数据库,然后我收到错误。有什么想法吗?
private void WRTODB_Click(object sender, EventArgs e)
{
OleDbConnection machStopDB = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+@"C:\Users\sgarner\Google Drive\Visual Studio 2012\Timer test\WRITE TO DB\WRITE TO DB\Machine_Stop.accdb");
machStopDB.Open();
string str = "INSERT INTO DV1(TIME,CODE,REASON)" +
"VALUES( ('" + DateTime.Now + "'),('" + textBox1.Text + "'),('" + textBox2.Text + "'))";
OleDbCommand insertCmd = new OleDbCommand(str, machStopDB);
insertCmd.ExecuteNonQuery();
machStopDB.Close();
}
这只是我正在使用的测试程序。
答案 0 :(得分:1)
以下代码包含了上述评论提供的完善的想法:
private void WRTODB_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection dbConnection = new SqlConnection())
{
string Source = @"C:\Users\sgarner\Google Drive\Visual Studio 2012\Timer test\WRITE TO DB\WRITE TO DB\Machine_Stop.accdb";
dbConnection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Source;
dbConnection.Open();
using (SqlCommand command = new SqlCommand("INSERT INTO DV1([TIME],CODE,REASON) VALUES ([pTime],[pCode],[pReason])", dbConnection))
{
command.Parameters.AddWithValue("pTime", DateTime.Now);
command.Parameters.AddWithValue("pCode", textBox1.Text);
command.Parameters.AddWithValue("pReason", textBox2.Text);
command.ExecuteNonQuery();
}
dbConnection.Close();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}