C# sql语句使用参数

.Net

string sql = "insert into Students (StudentName, Age) Values(@StudentName, @Age)";
//创建参数数组
SqlParameter[] parameter = new SqlParameter[]
{
new SqlParameter("@StudentName",objStudent.StudentName),
new SqlParameter("@Age",objStudent.Age)
};
try
{ //调用带参数方法
return SQLHelper.Update(sql,parameter);
}
catch (Exception ex)
{
throw new Exception("保存数据出现问题" + ex.Message);
}

/// 执行增、删、改 (带参数的SQL语句)
///
public static int Update(string sql,SqlParameter[] parameter)
{
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
cmd.Parameters.AddRange(parameter);//添加参数数组
return cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
}

我的博客,记录,笔记