在c#中執行sql語句時,避免會遇到傳參的問題。Parameters就是用來做參數化查詢,不然很容易被黑客拿到數據。
一、簡介
引用自:https://msdn.microsoft.com/ZH-CN/library/system.data.sqlclient.sqlcommand.parameters(v=vs.110).aspx
命名空間: System.Data.SqlClient
程序集: System.Data(位於 System.Data.dll)
語法
public SqlParameterCollection Parameters { get; }
屬性值
Type: System.Data.SqlClient.SqlParameterCollection
Transact-SQL 語句或存儲過程的參數。 默認值為空集合。
二、示例
private static void UpdateDemographics(Int32 customerID, string demoXml, string connectionString) { // Update the demographics for a store, which is stored // in an xml column. string commandText = "UPDATE Sales.Store SET Demographics = @demographics " + "WHERE CustomerID = @ID;"; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(commandText, connection); command.Parameters.Add("@ID", SqlDbType.Int); command.Parameters["@ID"].Value = customerID; // Use AddWithValue to assign Demographics. // SQL Server will implicitly convert strings into XML. command.Parameters.AddWithValue("@demographics", demoXml); try { connection.Open(); Int32 rowsAffected = command.ExecuteNonQuery(); Console.WriteLine("RowsAffected: {0}", rowsAffected); } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
三、常見用法
1. 分頁查詢
如下定義, 如果在查詢數據語句和查詢總條數中使用,會在第二處提示被引用的異常
List<SqlParameter> parameters = new List<SqlParameter>() ;
解決方法:
parameters.Select(x => ((ICloneable)x).Clone()).ToArray<object>()
2. Like的用法
原因是傳入的參數會被自動加上單引號,直接使用 Title like '%@Title%'會出錯
if (!string.IsNullOrEmpty(Title)) { keyCondition += " and (Title like @Title ) "; parameters.Add(new SqlParameter() { ParameterName = "@Title", Value = "%" + Title + "%" }); }
