[英]How to create optional parameters using object array
I am creating a method which MUST be use with or without parameters. 我正在创建必须与参数一起使用或不与参数一起使用的方法。 I am using object array so that I can hold string, integer, binary types, etc at the same time.
我正在使用对象数组,以便可以同时容纳字符串,整数,二进制类型等。
Method: SQLDB_UsingReader(string strSQL_WithParam, params object[,] obj) 方法: SQLDB_UsingReader(字符串strSQL_WithParam,params object [,] obj)
Error: The array must be a single dimensional array. 错误:数组必须是一维数组。
PS This method SQLDB_UsingReader(string strSQL_WithParam, object[,] obj) is working, but when I add " params " as the solution I searched when creating optional parameter, the error occurs. PS此方法SQLDB_UsingReader(string strSQL_WithParam,object [,] obj)有效,但是当我在创建可选参数时添加“ params ”作为搜索的解决方案时,会发生错误。
CODE 码
public void SQLDB_UsingReader(string strSQL_WithParam, params object[,] obj)
{
try
{
using (SqlCommand mCmd = new SqlCommand(strSQL_WithParam, mConn))
{
for (int i = 0; i < obj.Length / 2; i++)
{
if (obj[i, 1] == null || obj[i, 1].ToString() == "" || obj[i, 1].ToString().Length == 0)
{ mCmd.Parameters.Add(new SqlParameter(obj[i, 0].ToString(), DBNull.Value)); }
else
{ mCmd.Parameters.Add(new SqlParameter(obj[i, 0].ToString(), obj[i, 1])); }
}
mConn.Open();
mDataReader = mCmd.ExecuteReader();
mConn.Close();
}
}
catch (Exception ex) { ex.ToString(); }
}
Use Dictionary<string, object>
. 使用
Dictionary<string, object>
。 You have two values: a string and an object per parameter you wish to set. 您有两个值:每个参数要设置的字符串和对象。 Either create a class that has one of each and use params for an array of that class or simply use the built in type for a collection of named values.
创建一个每个都有一个的类,并为该类的数组使用参数,或者仅将内置类型用于命名值的集合。
public void SQLDB_UsingReader(string strSQL_WithParam, IDictionary<string, object> obj)
{
try
{
string where = obj.Any() ? ("where " + string.Join("AND", obj
.Select(x => x.Key +"==@" + x.Key)) : "";
using (SqlCommand mCmd = new SqlCommand(strSQL_WithParam + where, mConn))
{
foreach pair in obj
{
... (use pair.Value and pair.Key)
}
...
}
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.