日期:2014-05-18 浏览次数:20412 次
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; } } } }