我想使用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())
{
}
答案 0 :(得分:3)
我不知道我是否明白你在问什么,但你的意思是:
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();
}
使用示例可能是
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();
答案 1 :(得分:1)
FlyingStreudel的答案很好,但我已经修改了这个代码来制作演示最佳实践的版本(底部的链接。)您还可以使用Microsoft的企业库,它将为您提供强大的数据访问类。
private string _connectionString = "yourconnectionstring"; // from web.config, or wherever you store it
public static SqlDataReader executeProcedure(string commandName,
Dictionary<string, object> params)
{
SqlConnection conn = new SqlConnection(_connectionString);
conn.Open();
SqlCommand comm = conn.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(System.Data.CommandBehavior.CloseConnection);
}
使用,像这样:
Dictionary<string, object> paras = new Dictionary<string, object>();
paras.Add("user_name", "Timmy");
paras.Add("date", DateTime.Now);
using(SqlDataReader results = executeProcedure("sp_add_user", paras))
{
while (results.Read())
{
//do something with the rows returned
}
}
参考文献:
How Microsoft use Connections in Enterprise Library
答案 2 :(得分:0)
using (SqlConnection sqlConnection1 = new SqlConnection("Your Connection String")) {
using (SqlCommand cmd = new SqlCommand()) {
Int32 rowsAffected;
cmd.CommandText = "StoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
rowsAffected = cmd.ExecuteNonQuery();
}}
答案 3 :(得分:0)
如果您希望重用这种代码,一种可能的解决方案是将这种方法(执行存储过程并返回结果的方法)包装到应用程序的通用数据访问层中。您必须考虑的变化是不返回结果或期望参数的过程。
例如,您可以将此shell代码包装为ExecuteProcedure(),它需要连接字符串返回数据库。有许多其他方法可以完成这类任务,因此您需要确定哪种方法最适合您的特定要求。
答案 4 :(得分:0)
您可以包装此代码并将该过程作为参数。像这样:
public SqlCommand GetData(string procedure)
{
var conn = new SqlConnection(connectionString);
var cmd = new SqlCommand(procedure, conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
return cmd;
}
此方法的唯一问题是您没有正确处理资源,并且依赖于调用者来执行此操作。