- 注册时间
- 2014-1-13
- 最后登录
- 2014-4-1
- 阅读权限
- 10
- 积分
- 204
- 精华
- 0
- 帖子
- 76
|
本帖最后由 webyao 于 2014-2-23 23:31 编辑
treegrid提交的数据,做数据插入时,想把Hashtable user中的数据拼成一条SQL语句要怎么传递参数。
在事务里需要在同一连接下传递一批SQL语句,参数不好传递,在业务逻辑层,拼接时参数该如何传?
public static int ExecuteSqlTran(List<String> SQLStringList)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
SqlTransaction tx = conn.BeginTransaction();
cmd.Transaction = tx;
try
{
int count = 0;
for (int n = 0; n < SQLStringList.Count; n++)
{
string strsql = SQLStringList[n];
if (strsql.Trim().Length > 1)
{
cmd.CommandText = strsql;
count += cmd.ExecuteNonQuery();
}
}
tx.Commit();
return count;
}
catch
{
tx.Rollback();
return 0;
}
}
}
参照了private static void SetArgs(string sql, Hashtable args, IDbCommand cmd),但需要把Hashtable user整体作为参数传递。能不能直接在业务逻辑层,直接拼成一条SQL语句?
我试过这样传,可第二条sql语句的参数,读不到
public static int ExecuteSqlTran(List<String> SQLStringList, Hashtable args)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
SqlTransaction tx = conn.BeginTransaction();
cmd.Transaction = tx;
try
{
int count = 0;
for (int n = 0; n < SQLStringList.Count; n++)
{
string strsql = SQLStringList[n];
if (strsql.Trim().Length > 1)
{
MatchCollection ms = Regex.Matches(strsql, @"@\w+");
int i = 1;
foreach (Match m in ms)
{
string key = m.Value;
Object value = args[key];
if (value == null)
{
value = args[key.Substring(1)];
}
if (value == null) value = DBNull.Value;
cmd.Parameters.Add(new SqlParameter(key, value));
}
cmd.CommandText = strsql;
cmd.ExecuteNonQuery();
}
}
tx.Commit();
return count;
}
catch
{
tx.Rollback();
return 0;
}
}
}
|
|