SqlConnection cn = new SqlConnection(connectionString);
private SqlConnection CreatConntion()
{
try
{
if (cn.State=ConnectionState.Closed)
{
cn.Open();
}
}
catch(Exception e)
{
cn.Close();
throw new Exception(e.Message);
}
}
private SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
{
SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
command.Parameters.Add(new SqlParameter("ReturnValue",
SqlDbType.Int, 4, ParameterDirection.ReturnValue,
false, 0, 0, string.Empty, DataRowVersion.Default, null));
return command;
}
private SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
{
SqlCommand command = new SqlCommand(storedProcName, connection);
command.CommandType = CommandType.StoredProcedure;
foreach (SqlParameter parameter in parameters)
{
if (parameter != null)
{
if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
(parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
command.Parameters.Add(parameter);
}
}
return command;
}
public static int RunProcedure(string procName, SqlParameter[] cmdParms)
{
using (SqlConnection conn = CreatConntion())
{
using (SqlCommand comm = BuildIntCommand(conn, procName, cmdParms))
{
try
{
int result = comm.ExecuteNonQuery();
return result;
}
catch (Exception er)
{
//throw new Exception(er.Message);
return -1;
}
}
}
}以上代码这样写有好么?会不会出现异常?还有try,有人告诉我越小范围越好,是这样吗?
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货