所谓的连贯操作,类似于 mysql.table("table").where("1").find()。我不太喜欢为了写个查询,写多行语句。所以封装了一下。
框架为.net framework4,mysql.data.dll也是基于此框架。最低可用在XP系统上。最高目前为win10可用。
封装代码:
using System;
using System.Collections.Generic;
using System.Data;
using MySql.Data.MySqlClient;
using System.Text.RegularExpressions;
using System.Collections;
using System.Diagnostics;
namespace WormMysql{
public struct Info{
public long Code;
public string Msg;
public long Ret_str;
public DataTable data;
}
public class Wm_Mysql {
private string _where = "";
private string _table = "";
private string _field = "*";
private string _join = "";
private string _limit = "";
private string _group = "";
private string _order = "";
private string _sql = "";
private string _having = "";
private string _db_prefix;
private string Db_host;
private string Db_user;
private string Db_pwd;
private string Db_db;
private Dictionary<string, IDictionary> field_struct;
private Info information;
private MySqlConnection conn;
private MySqlDataAdapter dataAdapter;
private MySqlCommand cmd;
public Wm_Mysql(string host, string user, string pwd, string database, string db_prefix) {
this._field = "*";
this.Db_host = host;
this.Db_user = user;
this.Db_pwd = pwd;
this.Db_db = database;
this._db_prefix = db_prefix;
conn = new MySqlConnection();
}
private Info Connect(){
bool PingResult = false;
try {
PingResult = conn.Ping();
}catch (Exception) {
}
if (PingResult) {
information.Code = 1;
information.Msg = "已连接无需连接";
return information;
}
try {
string constr = "Persist Security Info=False;server=" + Db_host + ";user id=" + Db_user + ";password=" + Db_pwd + ";database=" + Db_db + ";Allow Zero Datetime=True;Connect Timeout=360";
this.conn = new MySqlConnection();
conn.ConnectionString = constr;
this.conn.Open();
information.Code = 1;
information.Msg = "连接成功";
cmd = conn.CreateCommand();
return information;
} catch (Exception e) {
information.Code = -1;
information.Msg = e.Message;
return information;
}
}
public Wm_Mysql table(String Table_value, String Alias_value = "") {
_table = _db_prefix + Table_value;
if(Alias_value != ""){
_table += " as " + Alias_value;
}
return this;
}
private Info BuildSql(){
if(_table == ""){
information.Code=-1;
information.Msg = "没有指定表名";
} else {
string sql = "SELECT " + _field + " FROM " + _table + (_join != "" ? _join : "") + (_where != "" ? " WHERE" + _where : "") + (_group != "" ? " GROUP BY" + _group : "") + (_having != "" ? " having" + _having : "") + (_order != "" ? " ORDER BY" + _order : "") + (_limit != "" ? _limit : "");
information.Code = 1;
information.Msg =sql;
}
return information;
}
public Info find(){
if(_table==""){
information.Code = -1;
information.Msg = "没有指定表名";
return information;
}
this.limit(0, 1);
Info BuildResult = this.BuildSql();
if(BuildResult.Code<0){
information.Code = -2;
information.Msg = BuildResult.Msg;
return information;
}
string Sql = BuildResult.Msg;
this._sql = Sql;
Info Result = this._query(Sql);
return Result;
}
public Info find(string Sql) {
this._sql = Sql;
Info info = _query(Sql);
return info;
}
public Info query() {
if (_table == "") {
information.Code = -1;
information.Msg = "没有指定表名";
return information;
}
Info BuildResult = this.BuildSql();
if (BuildResult.Code < 0) {
information.Code = -2;
information.Msg = BuildResult.Msg;
return information;
}
string Sql = BuildResult.Msg;
this._sql = Sql;
Info Result = this._query(Sql);
return Result;
}
public Info query(string Sql) {
this._sql = Sql;
Info info = _query(Sql);
return info;
}
private Info IncDec(string Field, Int16 Action, double Number = 1){
if(_table == ""){
information.Code= -3;
information.Msg = "没有指定表名";
return information;
}
if(_where == ""){
information.Code = -4;
information.Msg = "SetInc、SetDec方法要求必须指定where条件";
return information;
}
string Sql = "UPDATE " + _table + " SET " + Field + "=" + Field + (Action == 1 ? '+' : '-') + Number + (_where != "" ? " WHERE" + _where : "");
_sql = Sql;
Info info = this._query(Sql);
return info;
}
public Info setInc(String Field, double Number = 1){
return IncDec(Field, 1, Number);
}
public Info setDec(String Field, double Number = 1) {
return IncDec(Field, 0, Number);
}
public Info count(string Field="*"){
if (_table == "") {
information.Code = -5;
information.Msg = "没有指定表名";
return information;
}
string sql;
if(Field != "*"){
sql = "SELECT COUNT(" + Field + ") as " + Field;
} else{
sql = "SELECT COUNT(" + Field + ")";
}
sql += " FROM " + _table + (_join != "" ? _join : "") + " WHERE" + (_where != "" ? _where : " 1") + (_group != "" ? " GROUP BY " + _group : "" ) + ( _having != "" ? " having" + _having : "" );
_sql = sql;
Info info= this._query(sql);
return info;
}
public Info _sum(string Sql_str) {
if (_field != "*" && _field != "") {
Sql_str += "," + _field;
}
string sql = "SELECT " + Sql_str + " FROM " + _table + (_join != "" ? _join:"") + (_where != "" ? " WHERE" + _where : "") + (_group != "" ? " GROUP BY " + _group : "") + (_having != "" ? " having" + _having : "");
_sql = sql;
Info info = this._query(sql);
return info;
}
public Info sum(string Param) {
string sql = "sum(" + Param + ") as " + Param;
return _sum(sql);
}
public Info sum(string[,] Param) {
string Sql_str = "";
if (_table == "") {
information.Code = -7;
information.Msg = "没有指定表名";
return information;
}
int Length = Param.GetLength(0);
for (int i= 0; i < Length; i++){
Sql_str += "sum(" + Param[i, 0] + ") as " + Param[i, 1] + ",";
}
Int32 pos = Sql_str.LastIndexOf(',');
Sql_str = Sql_str.Substring(0, pos);
return _sum(Sql_str);
}
public Info execute(string Sql) {
_sql = Sql;
Info info = this._query(Sql);
return info;
}
public Info add(string[,] Data, bool Replace){
bool getFieldResult;string exeCmd; Info result; string Sql;
if (_table == "") {
information.Code = -8;
information.Msg = "没有指定表名";
return information;
}
if (Data.GetLength(0) == 0) {
information.Code = -9;
information.Msg = "要写入的数据是空的";
return information;
}
if(field_struct == null){
getFieldResult = this.GetFields(_table);
} else{
getFieldResult = true;
}
if(getFieldResult == false){
information.Code = -10;
information.Msg = "无法获取表的结构";
return information;
}
if (Replace == false) {
exeCmd = "INSERT INTO ";
} else {
exeCmd = "REPLACE INTO ";
}
Sql = exeCmd + _table + " SET " + _implode(Data, ",");
_sql = Sql;
result = this._query(Sql);
return result;
}
public Info save(string[,] Data) {
if(_table == ""){
information.Code = -11;
information.Msg = "没有指定表名";
return information;
}
if(_where == ""){
information.Code = -12;
information.Msg = "save方法要求必须指定where条件";
return information;
}
if (Data.GetLength(0) == 0) {
information.Code = -13;
information.Msg = "要保存的数据是空的";
return information;
}
string Sql_str; bool getFieldResult;
getFieldResult = GetFields(_table);
if (getFieldResult == false) {
information.Code = -14;
information.Msg = "无法获取表的结构" + _table;
return information;
}
Sql_str = "UPDATE " + _table + " SET " + _implode(Data, ",") + " WHERE" + _where;
_sql = Sql_str;
information = _query(Sql_str);
return information;
}
public Info delete(){
if(_table==""){
information.Code = -15;
information.Msg = "没有指定表名";
return information;
}
if(_where == ""){
information.Code = -16;
information.Msg = "delete方法要求必须指定where条件";
return information;
}
string sql = "DELETE FROM " + _table + " WHERE" + _where;
_sql = sql;
information = _query(sql);
return information;
}
public Info addall(string[,,] Data, bool Replace){
string Keys = "", Value, Values_last = "", Sql; Info Result = new Info(); bool getFieldResult;
ushort i,j;
if(field_struct == null) {
getFieldResult = GetFields(_table);
} else if(field_struct.Count == 0) {
getFieldResult = GetFields(_table);
} else{
getFieldResult = true;
}
if(getFieldResult == false){
Result.Code = -17;
Result.Msg = "无法获取表的结构";
return Result;
}
for(i = 0; i < Data.GetLength(1); i++) {
if(Data[0, i, 0] != null) {
if(field_struct.ContainsKey(Data[0, i, 0])){
Keys += "`" + Data[0, i, 0] + "`" + ",";
}
}
}
if(Keys != ""){
Keys = "(" + Keys.Substring(0, Keys.Length - 1) + ")";
} else{
Result.Code = -18;
Result.Msg = "获取表结构时未能获取字段信息" + Keys;
return Result;
}
for(i = 0; i < Data.GetLength(0); i++) {
Value = "";
for(j = 0; j < Data.GetLength(1); j++) {
if(Data[i, j, 0] != null) {
if(field_struct.ContainsKey(Data[i, j, 0])){
Value += _quote(Data[i, j, 1], field_struct[Data[i, j, 0]]["Type"].ToString()) + ",";
}
}
}
if(Value != ""){
Values_last += "(" + Value.Substring(0, Value.Length - 1) + "),";
}
}
Values_last = Values_last.Substring(0, Values_last.Length - 1);
if(Values_last != ""){
Sql = (Replace == true ? "REPLACE INTO " : "INSERT INTO ") + _table + Keys + " values " + Values_last;
_sql = Sql;
return _query(Sql);
} else {
information.Code = -11;
information.Msg = "无法构建多个values数据,结果为空";
return information;
}
}
public Wm_Mysql field(string FieldValue){
_field = FieldValue;
return this;
}
public string getLastSql(){
return _sql;
}
public string GetLastSql() {
return _sql;
}
private string _implode(string[,] Data, string Glue = ",") {
string Sql_str = ""; string cmd = "";
string glue_final = " " + Glue + " ";
Int16 i;
int Length = Data.GetLength(0);
for (i = 0; i < Length; i++) {
if(Data[i, 0] != null){
if(field_struct.ContainsKey(Data[i, 0]) == true){
Sql_str += cmd + "`" + Data[i, 0] + "`" + "=" + _quote(Data[i, 1], field_struct[Data[i, 0]]["Type"].ToString());
}
cmd = glue_final;
}
}
return Sql_str;
}
private string _quote(string Str, string Type, bool Withquote = true) {
int Pos = Type.IndexOf("(");
if(Pos == -1) {
Type = Type.Substring(0, Type.Length);
} else {
Type = Type.Substring(0, Pos);
}
if(Type == "int" || Type == "bigint" || Type == "mediumint" || Type == "tinyint" || Type == "smallint" || Type == "decimal" || Type == "float" || Type == "double"){
if (Str == "" || Str == null) {
return "";
}
return Str;
}
if(Type == "tinytext" || Type == "text" || Type == "varchar" || Type == "char" || Type == "mediumtext" || Type == "longtext" || Type == "enum"){
return (Withquote ? "'" : "") + Str.Replace("\\", "\\\\").Replace("'", "\'") + (Withquote ? "'" : "");
}
return (Withquote ? "'" : "") + Str.Replace("\\", "\\\\").Replace("'", "\'") + (Withquote ? "'" : "");
}
public Wm_Mysql limit(Int32 Start_value, Int32 limit_value = 0){
Int32 limit_final = limit_value > 0 ? limit_value : 0;
Int32 start_final = Start_value > 0 ? Start_value : 0;
if (start_final > 0 && limit_final > 0) {
_limit = " LIMIT " + start_final + ", " + limit_final;
} else if (limit_final > 0) {
_limit = " LIMIT " + limit_final;
} else if (start_final > 0) {
_limit = " LIMIT " + start_final;
} else {
_limit = "";
}
return this;
}
public Wm_Mysql order(string Order_value) {
if(Order_value != ""){
_order = " " + Order_value.Trim();
}
return this;
}
public Wm_Mysql group(string Group_value) {
if(Group_value != ""){
_group = " " + Group_value.Trim();
}
return this;
}
public Wm_Mysql having(string having_value){
if(having_value != ""){
_having = " " + having_value.Trim();
}
return this;
}
public Wm_Mysql join(string Join_value) {
if(Join_value != ""){
Regex reg = new Regex("__(.*?)__");
string join_str = reg.Replace(Join_value, _db_prefix + "$1");
_join = " " + join_str;
}
return this;
}
public Wm_Mysql where(params string[] Items) {
if(Items.Length == 1) {
_where = " " + Items[0];
} else if(Items.Length == 0){
_where = "";
} else {
string result = _sprintf(Items);
_where = " " + result;
}
return this;
}
public int startTrans(){
this.Connect();
//conn.BeginTransaction();
int ret_code = 0;
cmd.Connection = conn;
cmd.CommandText = "SET AUTOCOMMIT=0;start transaction;";
ret_code = cmd.ExecuteNonQuery();
return ret_code;
}
public int rollback(){
int ret_code;
Connect();
cmd.Connection = conn;
cmd.CommandText = "rollback;";
ret_code = cmd.ExecuteNonQuery();
cmd.CommandText = "SET AUTOCOMMIT=1;";
cmd.ExecuteNonQuery();
return (ret_code);
}
public int commit(){
int ret_code;
cmd.Connection = conn;
cmd.CommandText = "SET AUTOCOMMIT=1;";
cmd.ExecuteNonQuery();
cmd.CommandText = "commit;";
ret_code = cmd.ExecuteNonQuery();
return (ret_code);
}
private Info _query(string Sql) {
string Sqlcmd = "";
this.Connect();
int Pos = Sql.IndexOf(" ");
Sqlcmd = Sql.Substring(0, Pos).ToUpper();
information.Msg = "ok";
try {
if(Sqlcmd == "UPDATE" || Sqlcmd == "DELETE" || Sqlcmd == "REPLACE" || Sqlcmd == "INSERT"){
long ret_code;
cmd.CommandText = Sql;
ret_code = cmd.ExecuteNonQuery();
if (Sqlcmd == "INSERT") {
ret_code = cmd.LastInsertedId;
} else if (Sqlcmd == "REPLACE") {
//不需要处理,直接调用上面的ret_code
if(cmd.LastInsertedId > 0){
ret_code = cmd.LastInsertedId;
}
}
if (ret_code > 0) {
information.Code = ret_code;
information.Ret_str = ret_code;
} else {
information.Code = -101;
information.Msg = "操作失败。ret_code=" + ret_code + "。your sql is " + Sql;
}
} else if(Sqlcmd == "SELECT"){
DataTable dataTable = new DataTable();
dataAdapter = new MySqlDataAdapter(Sql, conn);
MySqlCommandBuilder cb = new MySqlCommandBuilder(dataAdapter);
dataAdapter.Fill(dataTable);
information.Code = 1;
information.data = dataTable;
}
_where = "";
_table = "";
_field="";
_join="";
_limit = "";
_group = "";
_order = "";
_having = "";
field_struct = null;
} catch (Exception e) {
information.Code = -1000;
information.Msg = e.Message + "。your sql is " + Sql;
}
return information;
}
private bool GetFields(string TableName){
string Sql; DataTable dataTable = new DataTable();
if(TableName.Trim() == ""){
return false;
}
Sql = "SHOW COLUMNS FROM `" + TableName + "`";
try {
Connect();
dataAdapter = new MySqlDataAdapter(Sql, conn);
MySqlCommandBuilder cb = new MySqlCommandBuilder(dataAdapter);
dataAdapter.Fill(dataTable);
Dictionary<string, IDictionary> Fields = new Dictionary<string, IDictionary>();
foreach (DataRow row in dataTable.Rows) {
Dictionary<string, string> dc = new Dictionary<string,string>();
dc.Add("Field", row["field"].ToString());
dc.Add("Type", row["Type"].ToString());
dc.Add("Null", row["Null"].ToString());
dc.Add("Key", row["Key"].ToString());
Fields.Add(row["field"].ToString(), dc);
}
field_struct = Fields;
return true;
} catch(Exception) {
return false;
}
}
private string _sprintf(params string[] Items) {
int i;
int num = Items.Length;
string ostr = Items[0];
Regex reg = new Regex("%\\w?");
for(i = 1; i < num; i++) {
ostr = reg.Replace(ostr, _quote(Items[i].ToString(), "text", false), 1);
}
return ostr;
}
}
}
使用实例:
using System;
using WormMysql;
namespace ConsoleApp1 {
internal class Program {
static void Main(string[] args) {
Wm_Mysql Mysql = new Wm_Mysql("localhost", "root", "8270201212", "hzxn_shop", "h_");
//************************************************************************************************** 指定sql语句单条查询(也可以把find()改为query())
//Info i = Mysql.find("select nickname from h_user where uid=2");
//Console.WriteLine(i.data.Rows[0]["nickname"].ToString());
//************************************************************************************************** 普通单条查询
//Info i = Mysql.table("user").where("uid=2").find();
//Console.WriteLine(i.data.Rows[0]["nickname"].ToString());
//************************************************************************************************** join 查询(find改为query则是多条数据查询)
//Info i = Mysql.table("user", "user").where("user.uid=%d", "1").join("left join __user_count__ uc on user.uid=uc.uid").field("regdate, credit1").find();
//System.Diagnostics.Debug.WriteLine(Mysql.getLastSql());
//if(i.Code < 0) {
// System.Diagnostics.Debug.WriteLine("sql语句错误:" + i.Msg);
// return;
//} else if(i.data.Rows.Count == 0) {
// System.Diagnostics.Debug.WriteLine("没有查到数据。");
// return;
//}
//Console.WriteLine(i.data.Rows[0]["credit1"].ToString());
//************************************************************************************************** add插入数据
//string[,] data = {{"skey", "1111" }, {"svalue", "3333" }, {"openid", "2222" }, {"goodscount", "4444" }};
//Info i = Mysql.table("setting").add(data, true); //第二个参数指示是否替换插入
//Console.WriteLine(i.Code + "," + i.Msg );
//************************************************************************************************** addAll插入多行数据
//string [,,] data = new string[3,4,2]{
//{ { "fullname", "张三"}, { "password", "1111"}, { "age", "10"}, { "regdate", "123"} },
//{ { "fullname", "李四"}, { "password", "2222"}, { "age", "20"}, { "regdate", "456"} },
//{ { "fullname", "王五"}, { "password", "3333"}, { "age", "30"}, { "regdate", "789"} }
//};
//Info d = Mysql.table("user").addall(data, true);
//if(d.Code < 0) {
// Console.WriteLine(d.Code + "," + d.Msg );
//} else {
// Console.WriteLine(d.Code);//多条插入,返回值为插入的这多条记录的第一个记录的自增ID
//}
//************************************************************************************************** save保存
//string[,] data = { {"fullname", "卧槽" } };
//Info i = Mysql.table("user").where("uid=1").save(data);
//Console.WriteLine(i.Code);
//************************************************************************************************** 记录数
//Info d = Mysql.table("user").where("uid > 2").count();
//Console.WriteLine(d.data.Rows[0][0]);
//Console.WriteLine(Mysql.getLastSql());
//************************************************************************************************** 单列合计
//string param = "uid";
//Info d = Mysql.table("user").field("uid,fullname").where("uid>%d", "8").sum(param);
//Console.WriteLine(d.data.Rows[0][0]);
//foreach(DataRow myRow in d.data.Rows) {
// Console.WriteLine(myRow[0].ToString());
//}
//************************************************************************************************** 多列合计
//string[,] param = {
// { "regdate","reg"},
// {"uid", "uuuuid" }
//};
//Info d = Mysql.table("user").field("uid,fullname").where("uid>%d", "8").sum(param);
//Console.WriteLine(d.data.Rows[0][0]);
//Console.WriteLine(d.data.Rows[0][1]);
//Console.WriteLine(d.data.Rows[0]["reg"]);
//Console.WriteLine(d.data.Rows[0]["uuuuid"]);
//************************************************************************************************** execute
//Info d = Mysql.execute("update h_user set fullname='大老张' where uid=1");
//Console.WriteLine(d.Msg);
//************************************************************************************************** 事务、回滚、提交 和 修改
//Mysql.startTrans();
//string[,] data = { {"fullname", "卧槽9" } };
//Info d = Mysql.table("user").where("uid=1").save(data);
//Mysql.rollback();
//Mysql.commit();
//************************************************************************************************** 删除
//Info d = Mysql.table("user").where("uid=%d", "7953").delete();
//Console.WriteLine(d.Code);
Console.ReadKey();
}
}
}
想测试哪个功能就把哪个的注释符号删除。测试的时候注意数据安全性。不要误删、误修改数据
遇见有问题的地方,记得回复通知我。因为我测试也不是很完整。谢谢
这里不能上传xp可用的mysql.data.dll,大家可以自行安装mysql连接器,下载xp可用的版本。我这个版本是6.3.7.0。觉得麻烦可以下载我上传的资源: