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