How C#sql statements use placeholders

Source: Internet
Author: User

Background: In a program, when you write an SQL statement, you may want to vary the SQL statement depending on the value of the variable. For example, the existence of variable stuname, depending on the value of the variable, to retrieve the student records of different names, then need to the knowledge of the placeholder.

1,{0} placeholder, the code is as follows:

1             string sql=@ "select top 1 * from Student where stuname= ' {0} '"; 2             string " John Doe ");

The above code is in the Student data table, the student named "John Doe" record.

2, configure the parameters, the code is as follows:

 1  string  sql=@ " select top 1 * from Student where [email protected]   " ;  2  sqlparameter para = new  Sqlparamet ER () {parametername =   @stuName   ", Value = "   John Doe   " };  3  SqlCommand cmd = new   SqlCommand (SQL, conn);  4  cmd. Parameters.Add (para); 

The above code is consistent with the effect of the placeholder.

So how do you use multiple configuration parameters at the same time? The code is as follows:

1List<sqlparameter> paras =NewList<sqlparameter>();2paras. ADD (NewSqlParameter () {parametername ="@stuName", Value ="Lee" });3paras. ADD (NewSqlParameter () {parametername ="@city", Value ="BJ" });4             stringSql=@"Select top 1 * from Student where [email protected] and [email protected]";5SqlCommand cmd =NewSqlCommand (SQL, conn);6Cmd. Parameters.addrange (paras. ToArray <SqlParameter> ());

The above code is in the student data sheet, the student name is Lee and the city in Beijing Records.

How C#sql statements use placeholders

Related Article

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.