oledb数据库中的异常2147217900

时间:2016-01-07 02:44:10

标签: c# oledb oledbexception

我尝试使用之前计算过的文本框中的值更新数据库表。计算工作正常,文本框已转换为小数。:

        try
        {
            OleDbConnection con = new OleDbConnection();
            con.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\User\Desktop\esoft\gym\gym\bin\Debug\Clients.accdb;";
            con.Open();
            OleDbCommand com = new OleDbCommand();
            com.Connection = con;
            com.CommandText = "INSERT INTO gym ([BMI],[Health],[weight_change_to_healthy_bmi]) VALUES ('" + textBox5.Text + "','" + textBox6.Text + ",'" + textBox4.Text + "') WHERE ID='"+textBox2.Text+"',con";

            com.ExecuteNonQuery();
            MessageBox.Show("Saved");
            con.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error   " + ex);
        }

我得到的例外是:

  System.Data.OleDb.OleDbException was unhandled
  ErrorCode=-
  HResult=-2147217900
  Message=Syntax error (missing operator) in query expression ''Normal,'-3.750000000000000000000000001') WHERE ID='1111',con'.
  Source=Microsoft Access Database Engine
  StackTrace:
       at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)
       at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
       at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
       at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult)
       at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
       at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
       at gym.Form6.button3_Click(Object sender, EventArgs e) in C:\Users\User\Desktop\esoft\gym\gym\Form6.cs:line 95
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at gym.Program.Main() in C:\Users\User\Desktop\esoft\gym\gym\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

我将代码更改为:

 private void button3_Click(object sender, EventArgs e)
    {
     //   try
     //   {
            OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\User\Desktop\esoft\gym\gym\bin\Debug\Clients.accdb;");
           // con.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\User\Desktop\esoft\gym\gym\bin\Debug\Clients.accdb;";
            con.Open();
            OleDbCommand com = new OleDbCommand();
            com.Connection = con;
            com.CommandType = CommandType.Text;
            com.CommandText = "UPDATE gym ([BMI],[Health],[weight_change_to_healthy_bmi]) VALUES ('" + textBox5.Text + "','" + textBox6.Text + "','" + textBox4.Text + "') WHERE ID='" + textBox2.Text + "' ";

            com.ExecuteNonQuery();
            MessageBox.Show("Saved");
            con.Close();
     //   }
       // catch (Exception ex)
      //  {
       //     MessageBox.Show("Error   " + ex);
       // }

但行com.ExecuteNonQuery();

中没有语法错误

3 个答案:

答案 0 :(得分:3)

你在这里错过了一个撇号:

...','" + textBox6.Text + ",'"...

为了避免这些错误以及其他原因(如安全性),请参数化您的查询。

try
{
    using (var con = new OleDbConnection())
    {
        con.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\User\Desktop\esoft\gym\gym\bin\Debug\Clients.accdb;";
        con.Open();

        using (var com = new OleDbCommand())
        {
            com.Connection = con;
            com.CommandText = "INSERT INTO gym ([BMI],[Health],[weight_change_to_healthy_bmi]) VALUES (@bmi,@health,@weight)";
            com.Parameters.AddWithValue("@bmi", textBox5.Text);
            com.Parameters.AddWithValue("@health", textBox6.Text);
            com.Parameters.AddWithValue("@weight", textBox4.Text);

            com.ExecuteNonQuery();
        }
    }
    MessageBox.Show("Saved");
}
catch (Exception ex)
{
    MessageBox.Show("Not saved: " + ex.Message);
}

答案 1 :(得分:2)

“'”错过了撇号。

com.CommandText = "INSERT INTO gym ([BMI],[Health],[weight_change_to_healthy_bmi]) VALUES ('" + textBox5.Text + "','" + textBox6.Text + "','" + textBox4.Text + "') WHERE ID='"+textBox2.Text+"',con";

enter image description here

答案 2 :(得分:0)

如果您比较错误

''Normal,'-3.750000000000000000000000001') WHERE ID='1111',con'

包含您的源代码

'" + textBox6.Text + ",'" + textBox4.Text + "') WHERE ID='"+textBox2.Text+"',con";

您可以看到您的SQL查询因缺少单引号或双引号而结束

在这种情况下, textBox4.Text 似乎是-3.750000000000000000000000001

所以是的,你实际上错过了一个撇号:

...','" + textBox6.Text + ",'"...

为了避免这些错误以及其他原因(如安全性),请参数化您的查询。

try
{
    using (var con = new OleDbConnection())
    {
        con.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\User\Desktop\esoft\gym\gym\bin\Debug\Clients.accdb;";
        con.Open();

        using (var com = new OleDbCommand())
        {
            com.Connection = con;
            com.CommandText = "INSERT INTO gym ([BMI],[Health],[weight_change_to_healthy_bmi]) VALUES (@bmi,@health,@weight)";
            com.Parameters.AddWithValue("@bmi", textBox5.Text);
            com.Parameters.AddWithValue("@health", textBox6.Text);
            com.Parameters.AddWithValue("@weight", textBox4.Text);

            com.ExecuteNonQuery();
        }
    }
    MessageBox.Show("Saved");
}
catch (Exception ex)
{
    MessageBox.Show("Not saved: " + ex.Message);
}

这意味着您的任何字段上的单引号可以和事实上产生SQL INJECTION安全问题

如果您正在寻找一种名为UPSERT的行为(如果是新数据则执行INSERT,如果找到则执行UPDATE),您可以创建一个使用参数调用它的STORE PROCEDURE,或者您可以处理上层依赖的行为关于您的方法/架构指南