在实际开发中,我们不会直接使用拼写SQL语句的方法进行数据库操作,而是使用参数化的方法进行数据库操作,这样做的好处很多,不仅提高了程序的健壮性,同时也避免的SQL注入的问题。在这里,笔者为初学者提供一个SQLHelper模板,希望对新手有所启发。
public static class SqlHelper{public static readonly string strConn = ConfigurationManager.ConnectionStrings["strConn"].ConnectionString;public static int ExecuteNonQuery(string cmdText, params SqlParameter[] parameters){using (SqlConnection conn = new SqlConnection(strConn)){conn.Open();return ExecuteNonQuery(conn, cmdText, parameters);}}public static int ExecuteNonQuery(SqlConnection conn, string cmdText, params SqlParameter[] parameters){using (SqlCommand cmd = conn.CreateCommand()){cmd.CommandText = cmdText;cmd.Parameters.AddRange(parameters);return cmd.ExecuteNonQuery();}}public static object ExecuteScalar(string cmdText, params SqlParameter[] parameters){using (SqlConnection conn = new SqlConnection(strConn)){conn.Open();return ExecuteScalar(conn, cmdText, parameters);}}public static object ExecuteScalar(SqlConnection conn, string cmdText, params SqlParameter[] parameters){using (SqlCommand cmd = conn.CreateCommand()){cmd.CommandText = cmdText;cmd.Parameters.AddRange(parameters);return cmd.ExecuteScalar();}}public static DataTable ExecuteDataTable(string cmdText, params SqlParameter[] parameters){using (SqlConnection conn = new SqlConnection(strConn)){conn.Open();return ExecuteDataTable(conn, cmdText, parameters);}}public static DataTable ExecuteDataTable(SqlConnection conn, string cmdText, params SqlParameter[] parameters){using (SqlCommand cmd = conn.CreateCommand()){cmd.CommandText = cmdText;cmd.Parameters.AddRange(parameters);using (SqlDataAdapter adapter = new SqlDataAdapter(cmd)){DataTable dt = new DataTable();adapter.Fill(dt);return dt;}}}/// <summary>/// 存数据时防止为空/// </summary>/// <param name="value"></param>/// <returns></returns>public static object ToDbValue(this object value){return value == null ? DBNull.Value : value;}/// <summary>/// 取数据时防止为空/// </summary>/// <param name="value"></param>/// <returns></returns>public static object FromDbValue(this object value){return value == DBNull.Value ? null : value;}}