Joh*_*com 2 c# stored-procedures
我想使用 C# 调用存储过程。
我想为过程调用创建一个简写。
我仍然不想重新定义连接并打开它。如何创建方法 - 我仍然没有打开与数据库的连接?
我使用以下代码:
SqlConnection conn = null;
SqlDataReader rdr = null;
conn = new SqlConnection("");
conn.Open();
SqlCommand cmd = new SqlCommand("Procedure", conn);
cmd.CommandType = CommandType.StoredProcedure;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
}
Run Code Online (Sandbox Code Playgroud)
我不知道我是否明白你在问什么,但你的意思是这样的:
public static SqlReader executeProcedure(SqlConnection oConn, string commandName, Dictionary<string, object> params)
{
SqlCommand comm = oConn.CreateCommand();
comm.CommandType = CommandType.StoredProcedure;
comm.CommandText = commandName;
if (params != null)
foreach(KeyValuePair<string, object> kvp in params)
comm.Parameters.Add(new SqlParameter(kvp.Key, kvp.Value));
return comm.ExecuteReader();
}
Run Code Online (Sandbox Code Playgroud)
一个使用示例可能是
Dictionary<string, object> paras = new Dictionary<string, object>();
paras.Add("user_name", "Timmy");
paras.Add("date", DateTime.Now);
SqlReader results = executeProcedure(oConn, "sp_add_user", paras);
while (results.Read())
{
//do something with the rows returned
}
results.Close();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33630 次 |
| 最近记录: |