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()); }
}
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.
If
TargetWeight
,Height
, andTargetCalories
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.