简体   繁体   中英

Parameter not changing in OleDbCommand

This is a simple search page (search.aspx?title=Hello) and I want to query the db for like matches. According to the microsoft docs ( http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbparameter.aspx see: Remarks) this is the correct way to do it, but the parameter (?) never gets set to the value of the query string.

        string sqlcmd = "SELECT * FROM TableName WHERE Title LIKE ?";

        OleDbCommand command = new OleDbCommand(sqlcmd, sqlcon);

        OleDbParameter p1 = new OleDbParameter("@p1", OleDbType.WChar);
        p1.Value =  Request.QueryString["title"];         

        OleDbDataAdapter da = new OleDbDataAdapter(command);
        da.SelectCommand.Parameters.Add(p1);

        DataTable dt = new DataTable();
        da.Fill(dt);

The parameter never changes to what the query string was, it just executes the query

        SELECT * FROM Table WHERE Title LIKE ?

Could you try the following:

"SELECT * FROM Table WHERE Title LIKE @p1"

I think that is the convention when using parameters in ADO.Net command text.

Here is my solution, you need to have single quotes around the question mark for the SQL to work. Complete solution:

sqlcon.Open();

        string sqlcmd = "SELECT * FROM TableName WHERE Title LIKE '%?%'";

        OleDbCommand command = new OleDbCommand(sqlcmd, sqlcon);     

        command.Parameters.Add(new OleDbParameter("p1", Request.QueryString["Title"]));

        OleDbDataAdapter da = new OleDbDataAdapter(command);

        DataTable dt = new DataTable();
        da.Fill(dt);

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