SqlHelper模板
在实际开发中,我们不会直接使用拼写SQL语句的方法进行数据库操作,而是使用参数化的方法进行数据库操作,这样做的好处很多,不仅提高了程序的健壮性,同时也避免的SQL注入的问题。在这里,笔者为初学者提供一个SQLHelper模板,希望对新手有所启发。
1 public static class SqlHelper 2 { 3 public static readonly string strConn = ConfigurationManager.ConnectionStrings["strConn"].ConnectionString; 4 5 public static int ExecuteNonQuery(string cmdText, params SqlParameter[] parameters) 6 { 7 using (SqlConnection conn = new SqlConnection(strConn)) 8 { 9 conn.Open(); 10 return ExecuteNonQuery(conn, cmdText, parameters); 11 } 12 } 13 public static int ExecuteNonQuery(SqlConnection conn, string cmdText, params SqlParameter[] parameters) 14 { 15 using (SqlCommand cmd = conn.CreateCommand()) 16 { 17 cmd.CommandText = cmdText; 18 cmd.Parameters.AddRange(parameters); 19 return cmd.ExecuteNonQuery(); 20 } 21 } 22 23 public static object ExecuteScalar(string cmdText, params SqlParameter[] parameters) 24 { 25 using (SqlConnection conn = new SqlConnection(strConn)) 26 { 27 conn.Open(); 28 return ExecuteScalar(conn, cmdText, parameters); 29 } 30 } 31 public static object ExecuteScalar(SqlConnection conn, string cmdText, params SqlParameter[] parameters) 32 { 33 using (SqlCommand cmd = conn.CreateCommand()) 34 { 35 cmd.CommandText = cmdText; 36 cmd.Parameters.AddRange(parameters); 37 return cmd.ExecuteScalar(); 38 } 39 } 40 41 public static DataTable ExecuteDataTable(string cmdText, params SqlParameter[] parameters) 42 { 43 using (SqlConnection conn = new SqlConnection(strConn)) 44 { 45 conn.Open(); 46 return ExecuteDataTable(conn, cmdText, parameters); 47 } 48 } 49 public static DataTable ExecuteDataTable(SqlConnection conn, string cmdText, params SqlParameter[] parameters) 50 { 51 using (SqlCommand cmd = conn.CreateCommand()) 52 { 53 cmd.CommandText = cmdText; 54 cmd.Parameters.AddRange(parameters); 55 using (SqlDataAdapter adapter = new SqlDataAdapter(cmd)) 56 { 57 DataTable dt = new DataTable(); 58 adapter.Fill(dt); 59 return dt; 60 } 61 } 62 } 63 64 /// <summary> 65 /// 存数据时防止为空 66 /// </summary> 67 /// <param name="value"></param> 68 /// <returns></returns> 69 public static object ToDbValue(this object value) 70 { 71 return value == null ? DBNull.Value : value; 72 } 73 74 /// <summary> 75 /// 取数据时防止为空 76 /// </summary> 77 /// <param name="value"></param> 78 /// <returns></returns> 79 public static object FromDbValue(this object value) 80 { 81 return value == DBNull.Value ? null : value; 82 } 83 }