- C# code
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,有人告诉我越小范围越好,是这样吗?
------解决方案--------------------------------------------------------
try是越小范围越好,因为用try影响性能
------解决方案--------------------------------------------------------
try的范围也不是越小越好,有时还要兼顾代码的结构和可读性。
另外对SqlCommand用using意义不大。
public的是个静态方法,而其他private的都是非静态方法,类的静态方法可以调用本类的非静态方法吗?