把MySqlXXX的類更改為SqlXXX就可以成為sqlHelper.
另外C#也提供了MysqlHelper和sqlHelper,用起來也挺方便的。
1 public class MySqlHelper 2 { 3 private static readonly string connstr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString; 4 public MySqlConnection CreateConnection() 5 { 6 MySqlConnection conn = new MySqlConnection(connstr); 7 conn.Open(); 8 return conn; 9 } 10 public int ExecuteNonQuery(string sql,params MySqlParameter[]parameters) 11 { 12 using (MySqlConnection conn=CreateConnection()) 13 using(MySqlCommand cmd=conn.CreateCommand()) 14 { 15 cmd.CommandText = sql; 16 cmd.Parameters.AddRange(parameters); 17 return cmd.ExecuteNonQuery(); 18 } 19 } 20 public object ExecuteScalar(string sql,params MySqlParameter[]parameters) 21 { 22 using (MySqlConnection conn=CreateConnection()) 23 using (MySqlCommand cmd=conn.CreateCommand()) 24 { 25 cmd.CommandText = sql; 26 cmd.Parameters.AddRange(parameters); 27 return cmd.ExecuteScalar(); 28 } 29 30 } 31 32 public MySqlDataReader ExecuteReader(string sql,params MySqlParameter[]ps) 33 { 34 using (MySqlConnection conn=CreateConnection()) 35 using(MySqlCommand cmd=conn.CreateCommand()) 36 { 37 cmd.CommandText = sql; 38 if (ps!=null) 39 { 40 cmd.Parameters.AddRange(ps); 41 } 42 return cmd.ExecuteReader(); 43 } 44 } 45 public DataTable ExecuteDataTable(string sql,params MySqlParameter[]ps) 46 { 47 DataTable table = new DataTable(); 48 using (MySqlConnection conn=CreateConnection()) 49 using(MySqlCommand cmd=conn.CreateCommand()) 50 { 51 cmd.CommandText = sql; 52 if (ps!=null) 53 { 54 cmd.Parameters.AddRange(ps); 55 } 56 using ( MySqlDataAdapter adapter = new MySqlDataAdapter(cmd)) 57 { 58 adapter.Fill(table); 59 } 60 return table; 61 } 62 } 63 }