本类可以应对主流数据库的访问。
带参操作可以有效避免sql注入漏洞。
访问mysql的时候,需要使用到一个叫mysql.data.dll的类,大家可以自行在网上寻找。
代码如下:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Data; 7 using System.Data.Common; 8 using System.Data.OleDb; 9 using System.Data.SqlClient; 10 using System.Web; 11 using MySql.Data.MySqlClient; 12 13 namespace HC_DB//mysql待验证 14 { 15 public enum HcEnvironment { Win, Net }; 16 public enum Db_type { Access_mdb, Access_accdb, /*Excel_xls,*/ Excel_xlsx, SqlServer, MySql }; 17 public class Access 18 { 19 static HcEnvironment environment; 20 static Db_type db_type; 21 static string db_path,ip_add,user_name,user_pass,db_name; 22 static DbCommand this_command; 23 public static void init_db(HcEnvironment env,Db_type dbt,string dbpath)// @"\data\example1.mdb" 24 { 25 environment = env; 26 db_type = dbt; 27 db_path = dbpath; 28 } 29 public static void init_db(Db_type dbt, string ip_add1,string user_name1, string user_pass1, string db_name1) 30 { 31 db_type=dbt; 32 ip_add= ip_add1; 33 user_name= user_name1; 34 user_pass= user_pass1; 35 db_name= db_name1; 36 } 37 public static DataTable get_datatable(string s1) 38 { 39 DbConnection myconn = createConn(); 40 DbDataAdapter myda; 41 if (db_type == Db_type.SqlServer) 42 { 43 myda = new SqlDataAdapter(s1, (SqlConnection)myconn); 44 } 45 else if (db_type == Db_type.MySql) 46 { 47 myda = new MySqlDataAdapter(s1, (MySqlConnection)myconn); 48 } 49 else 50 { 51 myda= new OleDbDataAdapter(s1, (OleDbConnection)myconn); 52 } 53 DataSet myds = new DataSet(); 54 try 55 { 56 myconn.Open(); 57 myda.Fill(myds, "No1"); 58 myconn.Close(); 59 //myconn.Dispose(); 60 return myds.Tables["No1"]; 61 } 62 catch (Exception e1) 63 { 64 throw (e1); 65 } 66 } 67 public static int do_nonquery(string s1) 68 { 69 DbConnection myconn = createConn(); 70 DbCommand mycomm; 71 if (db_type == Db_type.SqlServer) 72 { 73 mycomm = new SqlCommand(s1, (SqlConnection)myconn); 74 } 75 else if (db_type == Db_type.MySql) 76 { 77 mycomm = new MySqlCommand(s1, (MySqlConnection)myconn); 78 } 79 else 80 { 81 mycomm = new OleDbCommand(s1, (OleDbConnection)myconn); 82 } 83 try 84 { 85 int c; 86 myconn.Open(); 87 c = mycomm.ExecuteNonQuery(); 88 myconn.Close(); 89 //myconn.Dispose(); 90 return c; 91 } 92 catch (Exception e1) 93 { 94 //HttpContext.Current.Response.Write("<script language='javascript' defer>alert('" + e1.ToString() + "');</script>"); 95 throw (e1); 96 //return false; 97 } 98 } 99 public static void set_Para(string para_name, object para_value) 100 { 101 Init_Command(); 102 //DbParameter para1; 103 if (db_type == Db_type.SqlServer) 104 { 105 //para1 = ((SqlCommand)this_command).Parameters.AddWithValue(para_name, OleDbType.Char); 106 ((SqlCommand)this_command).Parameters.AddWithValue(para_name, para_value); 107 } 108 else if (db_type == Db_type.MySql) 109 { 110 //para1 = ((MySqlCommand)this_command).Parameters.AddWithValue(para_name, MySqlDbType.VarChar); 111 ((MySqlCommand)this_command).Parameters.AddWithValue(para_name, para_value); 112 } 113 else 114 { 115 //para1 = ((OleDbCommand)this_command).Parameters.AddWithValue(para_name, OleDbType.Char); 116 ((OleDbCommand)this_command).Parameters.AddWithValue(para_name, para_value); 117 } 118 return; 119 //para1.Value = para_value; 120 } 121 public static void set_comm(string sql) 122 { 123 Init_Command(); 124 this_command.CommandText = sql; 125 } 126 public static DataTable get_datatable()//重载,执行默认命令对象 127 { 128 DataTable thisdt = get_datatable(this_command); 129 this_command.Parameters.Clear(); 130 return thisdt; 131 } 132 public static int do_nonquery() 133 { 134 int thisint = do_nonquery(this_command); 135 this_command.Parameters.Clear(); 136 return thisint; 137 } 138 public static string get_para()//调试用 139 { 140 string s = ""; 141 for (int i = 0; i < this_command.Parameters.Count; i++) 142 { 143 s += this_command.Parameters[i].ParameterName + " " + this_command.Parameters[i].Value.ToString() + "\n"; 144 } 145 return s; 146 } 147 148 static DbConnection createConn()//返回access和excel的连接 149 { 150 string s1, s2; 151 if(db_type==Db_type.SqlServer) 152 { 153 s1 = $"server={ip_add};initial catalog={db_name};user ID={user_name};password={user_pass};"; 154 return new SqlConnection(s1); 155 } 156 else if(db_type==Db_type.MySql) 157 { 158 s1 = $"Database={db_name};Data Source={ip_add};User Id={user_name};Password={user_pass};allow zero datetime=true; Charset = utf8;Allow User Variables = True"; 159 //标准写法:myConnectionString = "Database=Test;Data Source=localhost;User Id=username;Password=pass"; 160 //另一种写法string mysql_url = "server=192.168.83.134;userid = root; database = hehe;port = 3306; password = test; Charset = utf8;Allow User Variables = True"; 161 return new MySqlConnection(s1); 162 } 163 if (db_type == Db_type.Access_mdb) 164 { 165 s1 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="; 166 } 167 else if (db_type == Db_type.Access_accdb||db_type==Db_type.Excel_xlsx) 168 { 169 s1 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="; 170 } 171 //else if(db_type==Db_type.Excel_xlsx) 172 //{ 173 // s1 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="; 174 //} 175 else 176 { 177 return null; 178 } 179 if (environment == HcEnvironment.Net) 180 { 181 s2 = HttpContext.Current.Server.MapPath(db_path); 182 } 183 else if (environment == HcEnvironment.Win) 184 { 185 s2 = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + db_path; 186 } 187 else 188 { 189 return null; 190 } 191 if(db_type==Db_type.Excel_xlsx) 192 { 193 s2+= ";Extended Properties='Excel 12.0;HDR=YES'";//HDR=YES表示有标题 194 } 195 OleDbConnection conn = new OleDbConnection(s1 + s2); 196 return conn; 197 } 198 static void Init_Command() 199 { 200 if (this_command == null) 201 { 202 if (db_type == Db_type.SqlServer) 203 { 204 this_command = new SqlCommand(); 205 } 206 else if (db_type == Db_type.MySql) 207 { 208 this_command = new MySqlCommand(); 209 } 210 else 211 { 212 this_command = new OleDbCommand(); 213 } 214 } 215 } 216 static DataTable get_datatable(DbCommand input_comm)//带参查询,例子见后面 217 { 218 input_comm.Connection = createConn(); 219 DbDataAdapter myda; 220 if (db_type == Db_type.SqlServer) 221 { 222 myda = new SqlDataAdapter((SqlCommand)input_comm); 223 } 224 else if (db_type == Db_type.MySql) 225 { 226 myda = new MySqlDataAdapter((MySqlCommand)input_comm); 227 } 228 else 229 { 230 myda = new OleDbDataAdapter((OleDbCommand)input_comm); 231 } 232 DataSet myds = new DataSet(); 233 try 234 { 235 myda.Fill(myds, "No1"); 236 return myds.Tables["No1"]; 237 } 238 catch (Exception e1) 239 { 240 throw (e1); 241 } 242 } 243 static int do_nonquery(DbCommand input_comm)//带参增删改,例子见方法后面 244 { 245 DbConnection myconn = createConn(); 246 input_comm.Connection = myconn; 247 try 248 { 249 int c; 250 myconn.Open(); 251 c = input_comm.ExecuteNonQuery(); 252 myconn.Close(); 253 //myconn.Dispose(); 254 return c; 255 } 256 catch (Exception e1) 257 { 258 //HttpContext.Current.Response.Write("<script language='javascript' defer>alert('" + e1.ToString() + "');</script>"); 259 throw (e1); 260 //return false; 261 } 262 } 263 } 264 }
使用方法:
//总体说明: //mysql 5.7,sqlserver 2005,access/excel 2007下调试通过。 //功能:对数据库执行查询字符串(普通和带参) //用法:引用dll(mysql要引用mysql.data.dll),namespace:HC_DB //初始化方法:Access.init_db(),静态类,一次初始化即可。在线数据库和文件数据库有重载方法。 //枚举说明: public enum HcEnvironment { Win, Net };//工作环境,net环境和非net环境 public enum Db_type { Access_mdb, Access_accdb, /*Excel_xls,*/ Excel_xlsx, SqlServer, MySql };//数据库类型,暂时懒得支持xls。 //excel说明: //若要引用完全使用的工作表的范围,请指定后面跟有美元符号的工作表名称。例如: //select * from [Sheet1$] //若要引用工作表上的特定地址范围,请指定后面跟有美元符号和该范围的工作表名称。例如: //select * from [Sheet1$A1:B10] //关于IMEX: //若为 0,则为输出模式,此情况下只能用作写入 Excel; //若为 1,则为输入模式,此情况下只能用作读取 Excel,并且始终将 Excel 数据作为文本类型读取; //若为 2,则为连接模式,此情况下既可用作写入、也可用作读取。 //所以若要读取混合数据类型,应该将 IMEX 设置为 1;若误设置为 0,则读取不到任何行;若误设置为 2 或省略,则有些数据读取出来是空白。 //注意:输出模式对应写入、输入模式对应读取。 //带参说明: //access里执行带参的update时,参数赋值顺序必须与语句中参数出现顺序一致。 string sql = "insert into t1(线路,票价) values(@a,@b)"; DataTable dt; Access.init_db(HcEnvironment.Win, Db_type.Access_accdb, @"\data\d1.accdb"); Access.set_Para("@a", "c->d"); Access.set_Para("@b", 55); Access.set_comm(sql); Access.do_nonquery(); sql="select * from t1 order by 票价 desc"; dt = Access.get_datatable(sql); for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < dt.Columns.Count; j++) { Console.Write(dt.Rows[i][j].ToString()); } Console.WriteLine(); } Console.ReadKey(); //mysql调用例程 string sql = "insert into t1 values(?a,?b,?c)"; DataTable dt; Access.init_db(Db_type.MySql,"127.0.0.1","root", "njnu123456","test"); Access.set_Para("@a",2); Access.set_Para("@b", "ls"); Access.set_Para("@c", 18); Access.set_comm(sql); Access.do_nonquery(); sql="select * from t1"; dt = Access.get_datatable(sql); for (int j = 0; j < dt.Columns.Count; j++) { Console.Write(dt.Columns[j].ColumnName+"\t"); } Console.WriteLine(); for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < dt.Columns.Count; j++) { Console.Write(dt.Rows[i][j].ToString()+"\t"); } Console.WriteLine(); } Console.ReadKey(); //sqlserver调用方法: string sql = "insert into t1 values(@a,@b,@c)"; DataTable dt; Access.init_db(Db_type.SqlServer, "127.0.0.1", "sa", "123456", "test"); Access.set_Para("@a", 4); Access.set_Para("@b", "xjb"); Access.set_Para("@c", 55); Access.set_comm(sql); Access.do_nonquery(); //其他 //sql存储过程用法 /*其他带参参数(存储过程)(未验证) SqlCommand comm=new SqlCommand() string sql = "proc_out"; comm.CommandText = sql; //把Command执行类型改为存储过程方式,默认为Text。 comm.CommandType = CommandType.StoredProcedure; //----------------------只用这里的东西,用exec proc的方式,也应该可以常规执行存储过程------------------------------------- //传递一个输入参数,需赋值 SqlParameter sp = comm.Parameters.Add("@uid", SqlDbType.Int); sp.Value = 4; //定义一个输出参数,不需赋值。Direction用来描述参数的类型 //Direction默认为输入参数,还有输出参数和返回值型。 sp = comm.Parameters.Add("@output", SqlDbType.VarChar, 50); sp.Direction = ParameterDirection.Output; //定义过程的返回值参数,过程执行完之后,将把过程的返回值赋值给名为myreturn的Paremeters赋值。 sp = comm.Parameters.Add("myreturn", SqlDbType.Int); sp.Direction = ParameterDirection.ReturnValue; dt1 = Hc_db.get_datatable1(mycomm);或Hc_db.do_nonquery1(my_comm);二选一 //--------------------------------------------------------- */ //基本sql语句 //INSERT INTO 表 [(字段1[,字段2[, ...]])] VALUES (值1[,值2[, ...])
几年前写着玩的东西了,备忘,也分享给有需要的人。