tai*_*ani 5 c# t-sql sqlcommand prepared-statement
我在WCF Web服务中有以下代码片段,它根据提供的字典值的格式构建一组where条件.
public static Dictionary<string, string>[] VehicleSearch(Dictionary<string, string> searchParams, int maxResults)
{
string condition = "";
foreach (string key in searchParams.Keys)
{
//Split out the conditional in case multiple options have been set (i.e. SUB;OLDS;TOY)
string[] parameters = searchParams[key].Split(';');
if (parameters.Length == 1)
{
//If a single condition (no choice list) check for wildcards and use a LIKE if necessary
string predicate = parameters[0].Contains('%') ? " AND {0} LIKE @{0}" : " AND {0} = @{0}";
condition += String.Format(predicate, key);
}
else
{
//If a choice list, split out query into an IN condition
condition += string.Format(" AND {0} IN({1})", key, string.Join(", ", parameters));
}
}
SqlCommand cmd = new SqlCommand(String.Format(VEHICLE_QUERY, maxResults, condition));
foreach (string key in searchParams.Keys)
cmd.Parameters.AddWithValue("@" + key, searchParams[key]);
cmd.Prepare();
Run Code Online (Sandbox Code Playgroud)
请注意,字典中的值显式设置为字符串,并且它们是发送到AddWithValue
语句中的唯一项.这会产生这样的SQL:
SELECT TOP 200 MVINumber AS MVINumber
, LicensePlateNumber
, VIN
, VehicleYear
, MakeG
, ModelG
, Color
, Color2
FROM [Vehicle_Description_v]
WHERE 1=1 AND VIN LIKE @VIN
Run Code Online (Sandbox Code Playgroud)
而错误说出来
System.InvalidOperationException:SqlCommand.Prepare方法要求所有参数都具有显式设置类型.
我所做的所有搜索都说我需要告诉AddWithValue
我正在准备的值的类型,但是我准备的所有值都是字符串,而且我看到的所有示例在处理字符串时都没有执行任何额外的操作.我错过了什么?
mar*_*c_s 11
而不是这个:
cmd.Parameters.AddWithValue("@" + key, searchParams[key]);
Run Code Online (Sandbox Code Playgroud)
你需要使用这样的东西:
cmd.Parameters.Add("@" + key, SqlDbType.******).Value = searchParams[key];
Run Code Online (Sandbox Code Playgroud)
您需要能够以某种方式确定您的参数必须是什么数据类型.
这可能是这样的:
SqlDbType.Int
对于整数值SqlDbType.VarChar
对于非Unicode字符串(不要忘记指定字符串的长度!)SqlDbType.UniqueIdentifier
对于Guids 使用AddWithValue
很方便 - 但是它可以让ADO.NET根据传入的值来猜测数据类型.大多数情况下,这些猜测非常好 - 但有时它们可能会关闭.
我建议你总是明确说出你想要的数据类型.
归档时间: |
|
查看次数: |
9594 次 |
最近记录: |