实现SqlParameter方式
因为通过SQL语句的方式,有时候存在脚本注入的危险,所以在大多数情况下不建议用拼接SQL语句字符串方式,希望通过SqlParameter实现来实现对数据的操作,针对SqlParameter的方式我们同样可以将其封装成一个可以复用的数据访问类,只是比SQL语句的方式多了一个SqlParameter的参数。
具体代码如下: -
-
-
-
- public static int ExecuteSql(string StrSql, params SqlParameter[] cmdParms)
- {
- using (SqlConnection connection = new SqlConnection(conString))
- {
- using (SqlCommand cmd = new SqlCommand())
- {
- PrepareCommand(cmd, connection, null, StrSql, cmdParms);
- int rows = cmd.ExecuteNonQuery();
- cmd.Parameters.Clear();
- return rows;
- }
- }
- }
-
-
-
-
- public static DataSet Query(string StrSql, params SqlParameter[] cmdParms)
- {
- using (SqlConnection connection = new SqlConnection(conString))
- {
- SqlCommand cmd = new SqlCommand();
- PrepareCommand(cmd, connection, null, StrSql, cmdParms);
- using (SqlDataAdapter da = new SqlDataAdapter(cmd))
- {
- DataSet ds = new DataSet();
- da.Fill(ds, "ds");
- cmd.Parameters.Clear();
- return ds;
- }
- }
- }
|