0

我有一个带有 [ID TIME CODE REASON] 列的表 (DV1) 的 Access 数据库。我只是想更新表格。我不断收到 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();
    }

这只是我正在使用的一个测试程序。

4

1 回答 1

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);
    }
}
于 2013-03-20T16:49:02.803 回答