FlyingStreudel 的回答很好,但我已经修改了该代码以制作演示最佳实践的版本(底部的链接)。您还可以使用 Microsoft 的 Enterprise Library,它将为您提供强大的数据访问类。
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
}
}
参考:
Microsoft 如何在企业库中使用连接
保持 SqlConnection 打开是 'foo bar'
从类中返回数据读取器