- public static int ExecuteNonQuery(string sql, params SqlParameter[] parameters)
- {
- string conStr = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
- SqlConnection conn = new SqlConnection(conStr);
- conn.Open();
- SqlCommand com = conn.CreateCommand();
- com.CommandText = sql;
- foreach (SqlParameter parameter in parameters)
- {
- com.Parameters.Add(parameter);
- }
-
- return com.ExecuteNonQuery();
- }
- /// <summary>
- /// 重载ExecuteScalar()
- /// </summary>
- /// <param name="sql"></param>
- /// <param name="parameters"></param>
- /// <returns></returns>
- public static object ExecuteScalar(string sql, params SqlParameter[] parameters)
- {
- string conStr = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
- SqlConnection conn = new SqlConnection(conStr);
- conn.Open();
- SqlCommand com = conn.CreateCommand();
- com.CommandText = sql;
- foreach (SqlParameter parameter in parameters)
- {
- com.Parameters.Add(parameter);
-
- }
- return com.ExecuteScalar();
- }
- public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] parameters)
- {
- string conStr = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
- SqlConnection conn = new SqlConnection(conStr);
- conn.Open();
- SqlCommand com = conn.CreateCommand();
- com.CommandText = sql;
- foreach (SqlParameter parameter in parameters)
- {
- com.Parameters.Add(parameter);
- }
- return com.ExecuteReader();
- }
- public static DataTable ExecuteDataTable(string sql, params SqlParameter[] parameters)
- {
- string conStr = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
- SqlConnection conn = new SqlConnection(conStr);
- conn.Open();
- SqlCommand com = conn.CreateCommand();
- com.CommandText = sql;
- foreach (SqlParameter parameter in parameters)
- {
- com.Parameters.Add(parameter);
- }
- DataSet ds = new DataSet();
- SqlDataAdapter adapter = new SqlDataAdapter(com);
- adapter.Fill(ds);
- //adapter.InsertCommand = conn.CreateCommand();
- //adapter.InsertCommand.CommandText = "..........";
- DataTable table = ds.Tables[0];
- return table;
- }
复制代码 foreach (SqlParameter parameter in parameters)
{
com.Parameters.Add(parameter);
}
这个循环式不能少的,因为你定义参数的时候params修饰的,参数的个数是不确定的,我的代码没有用using,其他都和你的差不多,希望对你有用 |