Reputation: 47
I have an Access DB with a table (DV1) that have [ID TIME CODE REASON] columns. I'm just trying to update the table. I keep getting a INSERT INTO sytax error. Everything I see looks fine. I've tried everything. I am opening the database, then I get the error. Any thoughts?
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();
}
This is just a test program I am working with.
Upvotes: 0
Views: 1636
Reputation: 10780
The following code incorporates the sound ideas offered by the comments above:
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);
}
}
Upvotes: 1