Syntax error in INSERT INTO statement in c# OleDb Exception cant spot the error

拜拜、爱过 提交于 2019-12-13 05:45:10

问题


EXACT duplicate of Syntax error in INSERT INTO statement in c# oledb?

Hi I cant spot the error. Please help. There is an OleDb Exception due to a Syntax Error. Syntax error in INSERT INTO statement OleDb Exception is unhandled.

    private OleDbConnection myCon;

    public Form1()
    {
        InitializeComponent();
        myCon = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C.mdb");
    }

private void insertuser_Click(object sender, EventArgs e)
    {
        try
        {
            OleDbCommand cmd = new OleDbCommand();
            myCon.Open();
            cmd.Connection = myCon;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "INSERT INTO User ([UserID], [Forename], [Surname], [DateOfBirth], [TargetWeight], [TargetCalories], [Height]) Values ('" + userid.Text + "' , '" + fname.Text + "' , '" + sname.Text + "' , '" + dob.Text + "' , '" + tarweight.Text + "' , '" + tarcal.Text + "' , '" + height.Text + "')";


            cmd.ExecuteNonQuery();
            myCon.Close();
        }
        catch (Exception ex) { MessageBox.Show(ex.ToString()); }



    }

回答1:


What are the values you're attempting to insert? Is height perhaps in feet and inches (5'10")? In which case you'll have closed the string (') and will have a syntax error.

And I agree wholeheartedly with @Brennan Vincent. Constructing raw SQL is not the way forward.




回答2:


If TargetWeight, Height, and TargetCalories are floating-point or integer values, they don't need to be surrounded by quotes in the SQL statement.

Also, not directly related to your question, but you should really consider using a parameterized query. Your code is very vulnerable to SQL injection.



来源:https://stackoverflow.com/questions/4628023/syntax-error-in-insert-into-statement-in-c-sharp-oledb-exception-cant-spot-the-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!