Usage of Asp.net parameters. addwithvalue in the where clause of SQL statements

Source: Internet
Author: User

The statement is as follows:

CopyCode The Code is as follows: View plaincopy to clipboardprint?
String strwhere = "'% % '";
Strsql = "select * from area where [name] Like @ strwhere"; // This cannot be used.
Cmd. Parameters. addwithvalue ("@ strwhere", strwhere );
String strwhere = "'% % '";
Strsql = "select * from area where [name] Like @ strwhere"; // This cannot be used.
Cmd. Parameters. addwithvalue ("@ strwhere", strwhere );

This is because ASP. net will add a single quotation mark after like when generating an SQL statement, resulting in an error. If you open the SQL Server tracking manager, you can see the executed statement as follows copy Code the code is as follows: exec sp_executesql n' select * from article where [title] Like @ strwhere ', n' @ strwhere nvarchar (5)', @ strwhere = n' % Why % '

it is not hard to understand that there are similar practices in olddbcommand.
the correct code is: copy Code the code is as follows: String connectionstring = @" provider = Microsoft. jet. oledb.4.0; Data Source = | datadirectory | \ aspxweb. MDB; ";
oledbconnection con = new oledbconnection (connectionstring);
con. open ();
oledbcommand cmd = new oledbcommand ();
cmd. connection = con;
string strwhere = "% Meng xianhui %";
string strsql = "select * from document where [author] Like @ strwhere ";
cmd. parameters. addwithvalue ("@ strwhere", strwhere);
cmd. commandtext = strsql;
oledbdatareader DR = cmd. executereader ();
while (dr. read ()
{< br> response. write (Dr ["author"] + ":" + Dr ["title"] + "
");
}< br> con. close ();
con. dispose ();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.