OleDBException error INSERT

醉酒当歌 提交于 2019-12-02 01:09:52

The reason for the syntax error is because Password, which happens to be the name of the column, is a reserved keyword.

insert into inlog ([PASSWORD], Username, leeftijd, gewicht)

From MS Access Docs,

If a reserved word is already in use, you can avoid error messages by surrounding each occurrence of the word with brackets ([ ]). However, the best solution is to change the name to a nonreserved word.

To further improved the code,

  • use using statement to properly dispose object
  • use try-catch to properly handle exceptions
  • parameterized the values to avoid sql injection

example,

string connStr = @"provider= microsoft.jet.oledb.4.0;data source=sample.mdb";
string test = "insert into inlog ([PASSWORD], Username, leeftijd, gewicht) VALUES (?, ?, ?, ?)";

using(OleDbConnection vcon = new OleDbConnection(connStr))
{
    using(OleDbCommand vcom = new OleDbCommand(test, vcon))
    {
        vcom.Parameters.AddWithValue("PASSWORD", textBox2.Text);
        vcom.Parameters.AddWithValue("Username", textBox1.Text);
        vcom.Parameters.AddWithValue("leeftijd", textBox3.Text);
        vcom.Parameters.AddWithValue("gewicht", textBox4.Text);
        try
        {
            vcon.Open();
            com.ExecuteNonQuery();
        }
        catch(OleDbException ex)
        {
            // do something with the exception
        }
    }
}

Use a try/catch block to catch the exception and see the errormessage. Also dispose of your resources in the finally block. The finally block will always be executed, even when an exception is thrown.

try
{
    OleDbConnection vcon = new OleDbConnection(@"provider= microsoft.jet.oledb.4.0;data source=sample.mdb");
    vcon.Open();

    string test = string.Format("insert into inlog (PASSWORD, Username, leeftijd, gewicht) VALUES ('" + textBox2.Text + "','" + textBox1.Text + "','" + textBox3.Text + "','" + textBox4.Text + "')");
    OleDbCommand vcom = new OleDbCommand(test, vcon);
    vcom.ExecuteNonQuery();
    MessageBox.Show("Uw gegevens zijn opgeslagen");
}
catch(Exception ex)
{
    MessageBox.Show(ex.Message);
}
finally
{
    vcom.Dispose();
    vcon.Close();
    vcon.Dispose();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!