我有以下代码连接到数据库 > 运行存储过程 > 然后继续。
我相信数据库编程很容易出错,所以防御很重要:以下是防御性的吗?(或者可以改进吗?)
public int RunStoredProc()
{
SqlConnection conn = null;
SqlCommand dataCommand = null;
SqlParameter param = null;
int myOutputValue;
try
{
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["IMS"].ConnectionString);
conn.Open();
dataCommand = conn.CreateCommand();
dataCommand.CommandType = CommandType.StoredProcedure;
dataCommand.CommandText = "pr_blahblah";
dataCommand.CommandTimeout = 200; //seconds
param = new SqlParameter();
param = dataCommand.Parameters.Add("@NumRowsReturned", SqlDbType.Int);
param.Direction = ParameterDirection.Output;
dataCommand.ExecuteNonQuery();
myOutputValue = (int)param.Value;
return myOutputValue;
}
catch (SqlException ex)
{
MessageBox.Show("Error:" + ex.Number.ToString(), "Error StoredProcedure");
return 0;
}
finally
{
if (conn != null)
{
conn.Close();
conn.Dispose();
}
}
}
现在的代码如下所示
我已经尝试使用每个人提供的所有帮助,并且上面的代码现在已经修改为以下我希望现在足够防御的代码:
public SqlConnection CreateConnection()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["IMS"].ConnectionString);
return conn;
}
public int RunStoredProc()
{
using (var conn = CreateConnection())
using (var dataCommand = conn.CreateCommand())
{
conn.Open();
dataCommand.CommandType = CommandType.StoredProcedure;
dataCommand.CommandText = "pr_BankingChargebacks";
dataCommand.CommandTimeout = 200; //5 minutes
SqlParameter param = new SqlParameter();
param = dataCommand.Parameters.Add("@NumRowsReturned", SqlDbType.Int);
param.Direction = ParameterDirection.Output;
dataCommand.ExecuteNonQuery();
int myOutputValue = (int)param.Value;
return myOutputValue;
}
}