SqlCommand.Parameters的使用
?在c#中執(zhí)行sql語句時(shí),避免會(huì)遇到傳參的問題。Parameters就是用來做參數(shù)化查詢,不然很容易被黑客拿到數(shù)據(jù)。
一、簡介
引用自: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 語句或存儲(chǔ)過程的參數(shù)。?默認(rèn)值為空集合。
二、示例
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. 分頁查詢
如下定義, 如果在查詢數(shù)據(jù)語句和查詢總條數(shù)中使用,會(huì)在第二處提示被引用的異常
List<SqlParameter> parameters = new List<SqlParameter>() ;解決方法:
parameters.Select(x => ((ICloneable)x).Clone()).ToArray<object>()2. Like的用法
原因是傳入的參數(shù)會(huì)被自動(dòng)加上單引號(hào),直接使用 Title like '%@Title%'會(huì)出錯(cuò)
if (!string.IsNullOrEmpty(Title)) { keyCondition += " and (Title like @Title ) ";parameters.Add(new SqlParameter() { ParameterName = "@Title", Value = "%" + Title + "%" }); }?
?
總結(jié)
以上是生活随笔為你收集整理的SqlCommand.Parameters的使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 008PHP文件处理——文件操作r w
- 下一篇: 灯的开关 Bulb Switcher I