在Access DB中添加INSERT INTO
本文关键字:INSERT INTO 添加 Access DB | 更新日期: 2023-09-27 18:04:49
我有一个Access DB表(DV1),有[ID TIME CODE REASON]列。我只是想更新一下表格。我一直得到一个INSERT INTO语法错误。我看到的一切都很好。我什么都试过了。我打开数据库,然后我得到错误。任何想法吗?
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();
}
这只是我正在使用的一个测试程序。
以下代码结合了上述注释提供的合理想法:
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);
}
}