Problem using sqlconnection in asp.net c#
My code:
String dbDate = DateTime.ParseExact(TextBox3.Text, "dd/mm/yyyy", null).ToString("yyyy-mm-dd");
SqlConnection MyConnection = new SqlConnection("Data Source=localhost;Initial Catalog=hcgoa;User Id=sa;Password=;");
MyConnection.Open();
String MyString = "select notice from notice_aspx where fil_no=? and orderdate=?";
SqlCommand MyCmd = new SqlCommand(MyString, MyConnection);
MyCmd.Parameters.AddWithValue("?", HiddenField4.Value);
MyCmd.Parameters.AddWithValue("?", dbDate);
using (SqlDataReader MyReader4 = MyCmd.ExecuteReader())
{
//**
if (MyReader4.Read())
{
String MyString1 = "UPDATE notice_aspx SET notice=? where fil_no=? AND orderdate=?";
SqlCommand MyCmd1 = new SqlCommand(MyString1, MyConnection);
MyCmd1.Parameters.AddWithValue("?", Editor1.Content.ToString());
MyCmd1.Parameters.AddWithValue("?", HiddenField4.Value.ToString());
MyCmd1.Parameters.AddWithValue("?", dbDate);
MyCmd1.ExecuteNonQuery();
}
else
{.........
ERROR is
Exception Details: System.Data.SqlClient.SqlException: Line 1: Incorrect syntax near '?'.
Line 1: Incorrect syntax near '?'.
How to correct the error. Is it because i cant use '?' ? Please help 开发者_运维问答to sort the problem.
I believe that for SQL server you need to use named parameters instead of positional parameters. See the documentation for SqlCommand.Parameters
for an example. So your SQL would be:
select notice from notice_aspx where fil_no=@fil and orderdate=@orderdate
(and you'd then specify those names when adding the parameters).
Note that this has nothing to do with ASP.NET - you should be able to check this in a small console app. (You should also have using
statements for your connection and command, btw.)
精彩评论