Reputation: 49
I'm trying to switch come of my SQL queries to parameter queries but i keep getting some errors shown after the code below:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//Define data objects
SqlConnection conn;
//SqlCommand comm;
//Read the connection string from web config
string connectionString = ConfigurationManager.ConnectionStrings["clientsConnectionString"].ConnectionString;
//Initialize the connection
conn = new SqlConnection(connectionString);
//Create Command
// comm = new SqlCommand();
const string SQL = "insert into request (Surname,[Other Names], mobileno, date, email, faculty, dept, [Registration Number], session, thesis, yearGrad, tellerno, amount, address, question ) values (@Surname,[@Other Names],@mobileno,@date, @email, @faculty, @dept, [@Registration Number], @session,@thesis, @yearGrad, @tellerno, @amount, @address,@question)";
SqlCommand cmd = new SqlCommand(SQL, conn);
cmd.Parameters.AddWithValue("@Surname", lblSurname.Text);
cmd.Parameters.AddWithValue("@[Other Names]", lblOtherNames.Text);
cmd.Parameters.AddWithValue("@mobileno", lblPhone.Text);
cmd.Parameters.AddWithValue("@date", lblDate.Text);
cmd.Parameters.AddWithValue("@email", lblEmail.Text);
cmd.Parameters.AddWithValue("@faculty", lblFaculty.Text);
cmd.Parameters.AddWithValue("@dept", lblDept.Text);
cmd.Parameters.AddWithValue("@[Registration Number]", lblRegNo.Text);
cmd.Parameters.AddWithValue("@session", lblSession.Text);
cmd.Parameters.AddWithValue("@thesis", lblThesis.Text);
cmd.Parameters.AddWithValue("@yearGrad", lblGradYr.Text);
cmd.Parameters.AddWithValue("@tellerno", lblTeller.Text);
cmd.Parameters.AddWithValue("@amount", lblAmount.Text);
cmd.Parameters.AddWithValue("@address", lblAdd.Text);
cmd.Parameters.AddWithValue("@question", lblQue.Text);
conn.Open();
// verify if the ID entered by the visitor is numeric
cmd.ExecuteNonQuery();
conn.Close();
//reload page if query executed succesfully
Response.Redirect("thanks.aspx");
}
}
Error message is:
Server Error in '/TranscriptReloaded' Application. Incorrect syntax near 'nvarchar'. Must declare the scalar variable "@date".
Upvotes: 2
Views: 357
Reputation: 1062550
Personally I would start by losing the @[two word]
variable names (which you also use as [@two word]
elsewhere). I don't know if this is the cause, but I have never seen this usage personally, and I'm dubious. Fine for column names (and table names), but variables? Not so sure. Changing the variable names is local to this code, so shouldn't cause any side-effects.
Upvotes: 2
Reputation: 7138
"date" is a SQL reserved word, so the translation to SQL may be having a problem with it. Generally speaking you should avoid using the word date on its own as column names or as parameters.
Upvotes: 3