简体   繁体   中英

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM