首先是在DAL数据访问层中的代码:
//数据更新的方法
public static int shuxing_update(s_passnature model)
{
string sql = "update s_passnature set pass_name=@pass_name,pass_content=@pass_content,pass_shuxing=@pass_shuxing,pass_shiledaddress=@pass_shiledaddress,pass_cost=@pass_cost,pass_company=@pass_company,is_start=@is_start,remark=@remark,operatorType=@operatorType where pass_id=@pass_id";
//sqlparameter对象添加
SqlParameter[] parameter = {
new SqlParameter("@pass_name",SqlDbType.VarChar,200),
new SqlParameter("@pass_content",SqlDbType.VarChar,5000),
new SqlParameter("@pass_shuxing",SqlDbType.VarChar,5000),
new SqlParameter("@pass_shiledaddress",SqlDbType.VarChar,5000),
new SqlParameter("@pass_cost",SqlDbType.Decimal),
new SqlParameter("@pass_company",SqlDbType.VarChar,100),
new SqlParameter("@is_start",SqlDbType.Int,4),
new SqlParameter("@remark",SqlDbType.VarChar,5000),
new SqlParameter("@operatorType",SqlDbType.VarChar,50),
new SqlParameter("@pass_id",SqlDbType.Int,4)
};
//对象赋值
parameter[0].Value = model.pass_name;
parameter[1].Value = model.pass_content;
parameter[2].Value = model.pass_shuxing;
parameter[3].Value = model.shiledaddress;
parameter[4].Value = model.pass_cost;
parameter[5].Value = model.pass_company;
parameter[6].Value = model.is_start;
parameter[7].Value = model.remark;
parameter[8].Value = model.operatorType;
parameter[9].Value = model.pass_id;
return Common.DbHelperSQL.ExecuteSql(sql, parameter);
}
dbhelper中的方法:
public static int ExecuteSql(string SQLString, params SqlParameter[] cmdParms)
{
using (SqlConnection conn = new SqlConnection(DbHelperSQL.connectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
try
{
DbHelperSQL. PrepareCommand(cmd,connection,(SqlTransaction)null,SQLString,cmdParms);
int num = cmd.ExecuteNonQuery();
//每次执行完以后必须的释放清理资源,否则或导致程序堵塞
cmd.Parameters.Clear();
return num;
}
catch (SqlException ex)
{
throw new Exception(ex.Message);
}
finally
{
cmd.Dispose();
conn.Close();
}
}
}
}
//数据验证带参数的语句都需要调用此方法进行验证
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = CommandType.Text;//cmdType;
if (cmdParms != null)
{
foreach (SqlParameter parameter in cmdParms)
{
if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
(parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
cmd.Parameters.Add(parameter);
}
}
}