EL323 EL323 - 2 months ago 17
ASP.NET (C#) Question

SqlException Incorrect syntax near '?'

I am getting sql exception in my query:


[SqlException (0x80131904): Incorrect syntax near '?'. Incorrect
syntax near the keyword 'User'.]


What am I doing wrong? And what does this exception means?

protected void Submit_Click(object sender, EventArgs e)
{
string myConnection = @"Data Source=REDDEVIL;Initial..."

SqlConnection conn = new SqlConnection(myConnection);

HttpPostedFile postedFile = FileUpload1.PostedFile;
string fileName = Path.GetFileName(postedFile.FileName);
string fileExtension = Path.GetExtension(fileName);

if (fileExtension.ToLower() == ".jpg" || fileExtension.ToLower() == ".bmp" ||
fileExtension.ToLower() == ".gif" || fileExtension.ToLower() == ".png")
{
Stream stream = postedFile.InputStream;
BinaryReader binaryReader = new BinaryReader(stream);
byte[] bytes = binaryReader.ReadBytes((int)stream.Length);

string query2 = "INSERT INTO Manager (ID,Name,Address,Phone,Cell,Email,DOB,Commission,Comments,Photo,User ID,IsActive) VALUES (?ID,?Name,?Address,?Phone,?Cell,?Email,?DOB,?Commission,?Comments,?Photo,?User_ID,?IsActive)";
SqlCommand cmd2 = new SqlCommand(query2, conn);
cmd2.Parameters.AddWithValue("?ID", mgrID.Text);
cmd2.Parameters.AddWithValue("?Name", Name.Text);
cmd2.Parameters.AddWithValue("?Address", address.Text);
cmd2.Parameters.AddWithValue("?Phone", phoneNo.Text);
cmd2.Parameters.AddWithValue("?Cell", CellNo.Text);
cmd2.Parameters.AddWithValue("?Email", email.Text);
cmd2.Parameters.AddWithValue("?DOB", dob.Text);
cmd2.Parameters.AddWithValue("?Commission", commission.Text);
cmd2.Parameters.AddWithValue("?Comments", comments.Text);
cmd2.Parameters.AddWithValue("?Photo", bytes);
cmd2.Parameters.AddWithValue("?User_ID", System.DBNull.Value);
cmd2.Parameters.AddWithValue("?IsActive", System.DBNull.Value);
conn.Open();
cmd2.ExecuteNonQuery();
conn.Close();

Response.Redirect("~/Views/Portal/Dashboard.aspx");
}
else
{
}
}


Any help will be much appreciated.

Answer

To specify that it is a parameter you should use @ instead of ? in your sql query. Then in your creation of the parameter, you do not need the ? either

string query2 = "INSERT INTO Manager (ID,Name,Address,Phone,Cell,Email,DOB,Commission,Comments,Photo,User_ID,IsActive) VALUES (@ID,@Name,@Address,@Phone,@Cell,@Email,@DOB,@Commission,@Comments,@Photo,@User_ID,@IsActive)";

SqlCommand cmd2 = new SqlCommand(query2, conn);
cmd2.Parameters.AddWithValue("ID", mgrID.Text);

And as Tim noticed in the section you are specifying the fields you have ...USER ID,.... - I assume you are missing a _ between the two. (of if it is indeed called user then see Tim's suggestion with the []

Comments