Chris
Chris

Reputation: 99

INSERT error ASP.NET

Hey I get an error saying there is something wrong with my code when inserting into a database, can't quite find it. The error suggests it is something in the INSERT statement, but appears on the line "cmd.ExecuteNonQuery();". I'm using an access database.

Error: Syntax error in INSERT INTO statement.

con.Open();
string mysql; 
mysql = "INSERT INTO [User](FirstName,Surname,Age,HouseNumber,PostCode,Username,Password) 
         VALUES (?,?,?,?,?,?,?)";
OleDbCommand cmd = new OleDbCommand(mysql, con);
cmd.Parameters.AddWithValue("@p1", tbFirstName.Text);
cmd.Parameters.AddWithValue("@p2", tbSurname.Text);
cmd.Parameters.AddWithValue("@p3", int.Parse(tbAge.Text));
cmd.Parameters.AddWithValue("@p4", tbAddress1.Text);
cmd.Parameters.AddWithValue("@p5", tbPostCode.Text);
cmd.Parameters.AddWithValue("@p6", tbUsername.Text);
cmd.Parameters.AddWithValue("@p7", tbPassword.Text);
cmd.ExecuteNonQuery();
con.Close();

Upvotes: 1

Views: 373

Answers (2)

Bearcat9425
Bearcat9425

Reputation: 1600

Have you tried replacing the ? with your parameters?

Correction: I believe you have to add OleDBParameters like so:

con.Open();
string mysql; 
mysql = "INSERT INTO User(FirstName,Surname,Age,HouseNumber,PostCode,Username,Password) 
     VALUES (@p1,@p2,@p3,@p4,@p5,@p6,@p7)";
OleDbCommand cmd = new OleDbCommand(mysql, con);
cmd.Parameters.AddRange(new OleDbParameter[]
{
    new OleDbParameter("@p1", tbFirstName.Text),
    new OleDbParameter("@p2", tbSurname.Text),
           ...
});
cmd.ExecuteNonQuery();
con.Close();

Upvotes: -1

Damith
Damith

Reputation: 63065

when you add parameters with value you need to convert it to matching type, if age is number then

cmd.Parameters.AddWithValue("@p3", int.Parse(tbAge.Text));

and also User is key word you can try with

"INSERT INTO [User] ([FirstName], [Surname], [Age], [HouseNumber], [PostCode], [Username], [Password]) VALUES (?,?,?,?,?,?,?)";

Upvotes: 5

Related Questions