0

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()); }



    }
7
  • 1
    Are you kidding us? Would you care to tell us what the error is? Commented Jan 7, 2011 at 16:53
  • 2
    Put brackets [] around the table name "User". It's a reserved word in SQL Server. Commented Jan 7, 2011 at 16:54
  • 1
    Please parameterize your query. Commented Jan 7, 2011 at 16:54
  • EXACT duplicate of Syntax error in INSERT INTO statement in c# oledb? Commented Jan 7, 2011 at 16:54
  • You've just ask this very question a few minutes ago - don't keep asking the same question over and over again! Commented Jan 7, 2011 at 16:55

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.