using System; using System.Collections; using System.Collections.Generic; using System.Data.SqlClient; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using MySql.Data.MySqlClient; using System.Configuration; using System.Xml; using System.Text.RegularExpressions; namespace WindowsFormsApp1 { public class DbHelperMySQL { /// /// 数据访问抽象基础类 /// Copyright (C) 2004-2008 By zzzili /// //数据库连接字符串(web.config来配置),可以动态更改connectionString支持多数据库. /// /// 获取连接字符串 /// public static string connectionString = GetConnectionStringFromXml("./SystemConfig.xml"); //"server=10.164.1.169;port=3306;user=root;password=3687988; database=mesdb_nca;";//GetConnectionStringFromXml("./SystemConfig.xml"); public static string DbName = getDbName();//"mesdb_nca"; public static string getDbName() { // 使用正则表达式提取数据库名称 string pattern = "database=([^;]+)"; Match match = Regex.Match(connectionString, pattern); if (match.Success) { string databaseName = match.Groups[1].Value; //Console.WriteLine(databaseName); // 输出: mesdb_nca return databaseName; } System.Windows.Forms.MessageBox.Show("获取数据库失败"); return ""; } public static string GetConnectionStringFromXml(string xmlFilePath) { try { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(xmlFilePath); XmlNodeList connectionNodes = xmlDoc.SelectNodes("//config"); foreach (XmlNode configNode in connectionNodes) { string name = configNode.Attributes["name"].Value; string ivalue = configNode.Attributes["ivalue"].Value; if (name.Equals("ConnString")) return ivalue; } throw new Exception("No connection string found in the XML file."); } catch (Exception ex) { throw new Exception("Error reading XML file: " + ex.Message); } } private MySqlConnection connection; /// /// DbHelperMySQL无参数构造函数 /// private DbHelperMySQL(MySqlConnection connection) { this.connection = connection; } #region 公用方法 /// /// 获取表中最大的Id值 /// /// 列名 /// 表名 /// public static int GetMaxID(string FieldName, string TableName) { string strsql = "select max(" + FieldName + ")+1 from " + TableName; object obj = GetSingle(strsql); if (obj == null) { return 1; } else { return int.Parse(obj.ToString()); } } /// /// 返回查询是否存在 /// /// 要查询的Sql语句 /// public static bool Exists(string strSql) { object obj = GetSingle(strSql); int cmdresult; if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if (cmdresult == 0) { return false; } else { return true; } } /// /// 返回查询是否存在 /// /// 查询语句 /// 参数互列表 /// public static bool Exists(string strSql, params MySqlParameter[] cmdParms) { object obj = GetSingle(strSql, cmdParms); int cmdresult; if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if (cmdresult == 0) { return false; } else { return true; } } #endregion #region 执行简单SQL语句 /// /// 返回新增加数据的Primary Key /// /// 要执行的INSERT SQL语句 /// 表名 /// 字段名 /// public static int ExecuteSqlReturnLastRowId(string SQLString, string TableName, string FieldName) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { using (MySqlCommand cmd = new MySqlCommand(SQLString, connection)) { try { connection.Open();//int rows = cmd.ExecuteNonQuery(); int a = GetMaxID(FieldName, TableName); return a; } catch (MySql.Data.MySqlClient.MySqlException e) { connection.Close(); throw new Exception(e.Message); } } } } /// /// 执行SQL语句,返回影响的记录数 /// /// SQL语句 /// 影响的记录数 public static int ExecuteSql(string SQLString) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { using (MySqlCommand cmd = new MySqlCommand(SQLString, connection)) { try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (MySql.Data.MySqlClient.MySqlException e) { connection.Close(); throw e; } } } } /// /// 指定时间执行 /// /// 执行语句 /// 时间 /// public static int ExecuteSqlByTime(string SQLString, int Times) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { using (MySqlCommand cmd = new MySqlCommand(SQLString, connection)) { try { connection.Open(); cmd.CommandTimeout = Times; int rows = cmd.ExecuteNonQuery(); return rows; } catch (MySql.Data.MySqlClient.MySqlException e) { connection.Close(); throw e; } } } } /// /// 执行多条SQL语句,实现数据库事务。 /// /// 多条SQL语句 public static int ExecuteSqlTran(List SQLStringList) { using (MySqlConnection conn = new MySqlConnection(connectionString)) { conn.Open(); MySqlCommand cmd = new MySqlCommand(); cmd.Connection = conn; MySqlTransaction tx = conn.BeginTransaction(); cmd.Transaction = tx; try { int count = 0; for (int n = 0; n < SQLStringList.Count; n++) { string strsql = SQLStringList[n]; if (strsql.Trim().Length > 1) { cmd.CommandText = strsql; count += cmd.ExecuteNonQuery(); } } tx.Commit(); return count; } catch { tx.Rollback(); return 0; } } } /// /// 执行带一个存储过程参数的的SQL语句。 /// /// SQL语句 /// 参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加 /// 影响的记录数 public static int ExecuteSql(string SQLString, string content) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { MySqlCommand cmd = new MySqlCommand(SQLString, connection); MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@content", SqlDbType.NText); myParameter.Value = content; cmd.Parameters.Add(myParameter); try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (MySql.Data.MySqlClient.MySqlException e) { throw e; } finally { cmd.Dispose(); connection.Close(); } } } /// /// 执行带一个存储过程参数的的SQL语句。 /// /// SQL语句 /// 参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加 /// 影响的记录数 public static object ExecuteSqlGet(string SQLString, string content) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { MySqlCommand cmd = new MySqlCommand(SQLString, connection); MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@content", SqlDbType.NText); myParameter.Value = content; cmd.Parameters.Add(myParameter); try { connection.Open(); object obj = cmd.ExecuteScalar(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (MySql.Data.MySqlClient.MySqlException e) { throw e; } finally { cmd.Dispose(); connection.Close(); } } } /// /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例) /// /// SQL语句 /// 图像字节,数据库的字段类型为image的情况 /// 影响的记录数 public static int ExecuteSqlInsertImg(string strSQL, byte[] fs) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { MySqlCommand cmd = new MySqlCommand(strSQL, connection); MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@fs", SqlDbType.Image); myParameter.Value = fs; cmd.Parameters.Add(myParameter); try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (MySql.Data.MySqlClient.MySqlException e) { throw e; } finally { cmd.Dispose(); connection.Close(); } } } //执行单条插入语句,并返回id,不需要返回id的用ExceuteNonQuery执行。 /// /// 执行插入语句并返回Id,不需返回Id的用其它执行方法 /// /// Sql语句 /// 此参数为Null时进行 /// public static int ExecuteInsert(string sql, MySqlParameter[] parameters) { //Debug.WriteLine(sql); using (MySqlConnection connection = new MySqlConnection(connectionString)) { MySqlCommand cmd = new MySqlCommand(sql, connection); try { connection.Open(); if (parameters != null) cmd.Parameters.AddRange(parameters); cmd.ExecuteNonQuery(); cmd.CommandText = @"select LAST_INSERT_ID()"; //此方法估计也可直接用 select @@identity 获得,两值基本都是全局服务,使用时不能关闭Connection int value = Int32.Parse(cmd.ExecuteScalar().ToString()); return value; } catch (Exception e) { throw e; } } } /// /// 执行一条计算查询结果语句,返回查询结果(object)。 /// /// 计算查询结果语句 /// 查询结果(object) public static object GetSingle(string SQLString) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { using (MySqlCommand cmd = new MySqlCommand(SQLString, connection)) { try { connection.Open(); object obj = cmd.ExecuteScalar(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (MySql.Data.MySqlClient.MySqlException e) { connection.Close(); throw e; } } } } /// /// 获取单一值 /// /// Sql语句 /// 时间 /// Object类型 public static object GetSingle(string SQLString, int Times) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { using (MySqlCommand cmd = new MySqlCommand(SQLString, connection)) { try { connection.Open(); cmd.CommandTimeout = Times; object obj = cmd.ExecuteScalar(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (MySql.Data.MySqlClient.MySqlException e) { connection.Close(); throw e; } } } } /// /// 执行查询语句,返回MySqlDataReader ( 注意:调用该方法后,一定要对MySqlDataReader进行Close ) /// /// 查询语句 /// MySqlDataReader public static MySqlDataReader ExecuteReader(string strSQL) { MySqlConnection connection = new MySqlConnection(connectionString); MySqlCommand cmd = new MySqlCommand(strSQL, connection); try { connection.Open(); MySqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); return myReader; } catch (MySql.Data.MySqlClient.MySqlException e) { throw e; } } /// /// 执行查询语句,返回DataTable /// /// 查询语句 /// DataTable public static DataTable Query(string SQLString) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { DataSet ds = new DataSet(); DataTable dt = new DataTable(); try { connection.Open(); MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection); command.Fill(ds, "ds"); dt = ds.Tables[0]; } catch (MySqlException ex) { throw new Exception(ex.Message); } return dt; } } /// /// 执行事务委托lambda语句,参数是DbHelperMySQL对象,通过执行对象的方法可以在事务的控制内 /// /// lambda语句 /// void public static void ExecuteTransaction(Action transactionAction) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { connection.Open(); using (MySqlTransaction transaction = connection.BeginTransaction()) { try { transactionAction.Invoke(new DbHelperMySQL(connection)); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); throw new Exception("Transaction failed: " + ex.Message); } } } } /// /// 执行SQL语句,返回影响的记录数 /// /// SQL语句 /// 影响的记录数 public static int ExecuteSql(MySqlConnection connection, string SQLString) { using (MySqlCommand cmd = new MySqlCommand(SQLString, connection)) { int rows = cmd.ExecuteNonQuery(); return rows; } } /// /// 执行SQL语句,返回影响的记录数 /// /// SQL语句 /// 影响的记录数 public int executeSql(string SQLString) { using (MySqlCommand cmd = new MySqlCommand(SQLString, this.connection)) { int rows = cmd.ExecuteNonQuery(); return rows; } } /// /// 执行语句,返回DataSet /// /// Sql语句 /// 时间 /// public static DataSet Query(string SQLString, int Times) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection); command.SelectCommand.CommandTimeout = Times; command.Fill(ds, "ds"); } catch (MySql.Data.MySqlClient.MySqlException ex) { throw new Exception(ex.Message); } return ds; } } #endregion #region 执行带参数的SQL语句 /// /// 执行SQL语句,返回影响的记录数 /// /// SQL语句 /// 准备好的参数列表 /// 影响的记录数 public static int ExecuteSql(string SQLString, params MySqlParameter[] cmdParms) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { using (MySqlCommand cmd = new MySqlCommand()) { try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); int rows = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return rows; } catch (MySql.Data.MySqlClient.MySqlException e) { throw e; } } } } /// /// 执行多条SQL语句,实现数据库事务。 /// /// SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[]) public static void ExecuteSqlTran(Hashtable SQLStringList) { using (MySqlConnection conn = new MySqlConnection(connectionString)) { conn.Open(); using (MySqlTransaction trans = conn.BeginTransaction()) { MySqlCommand cmd = new MySqlCommand(); try { //循环 foreach (DictionaryEntry myDE in SQLStringList) { string cmdText = myDE.Key.ToString(); MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Value; PrepareCommand(cmd, conn, trans, cmdText, cmdParms); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } trans.Commit(); } catch { trans.Rollback(); throw; } } } } /// /// 执行多条SQL语句,实现数据库事务。 /// /// SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[]) public static void ExecuteSqlTranWithIndentity(Hashtable SQLStringList) { using (MySqlConnection conn = new MySqlConnection(connectionString)) { conn.Open(); using (MySqlTransaction trans = conn.BeginTransaction()) { MySqlCommand cmd = new MySqlCommand(); try { int indentity = 0; //循环 foreach (DictionaryEntry myDE in SQLStringList) { string cmdText = myDE.Key.ToString(); MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Value; foreach (MySqlParameter q in cmdParms) { if (q.Direction == ParameterDirection.InputOutput) { q.Value = indentity; } } PrepareCommand(cmd, conn, trans, cmdText, cmdParms); int val = cmd.ExecuteNonQuery(); foreach (MySqlParameter q in cmdParms) { if (q.Direction == ParameterDirection.Output) { indentity = Convert.ToInt32(q.Value); } } cmd.Parameters.Clear(); } trans.Commit(); } catch { trans.Rollback(); throw; } } } } /// /// 执行一条计算查询结果语句,返回查询结果(object)。 /// /// 计算查询结果语句 /// 准备好的参数列表 /// 查询结果(object) public static object GetSingle(string SQLString, params MySqlParameter[] cmdParms) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { using (MySqlCommand cmd = new MySqlCommand()) { try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); object obj = cmd.ExecuteScalar(); cmd.Parameters.Clear(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (MySql.Data.MySqlClient.MySqlException e) { throw e; } } } } /// /// 执行查询语句,返回MySqlDataReader ( 注意:调用该方法后,一定要对MySqlDataReader进行Close ) /// /// 查询语句 /// 参数列表 /// public static MySqlDataReader ExecuteReader(string SQLString, params MySqlParameter[] cmdParms) { MySqlConnection connection = new MySqlConnection(connectionString); MySqlCommand cmd = new MySqlCommand(); try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); MySqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return myReader; } catch (MySql.Data.MySqlClient.MySqlException e) { throw e; } // finally // { // cmd.Dispose(); // connection.Close(); // } } /// /// 执行查询语句,返回DataSet /// /// 查询语句 /// 参数列表 /// DataSet public static DataSet Query(string SQLString, params MySqlParameter[] cmdParms) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { MySqlCommand cmd = new MySqlCommand(); PrepareCommand(cmd, connection, null, SQLString, cmdParms); using (MySqlDataAdapter da = new MySqlDataAdapter(cmd)) { DataSet ds = new DataSet(); try { da.Fill(ds, "ds"); cmd.Parameters.Clear(); } catch (MySql.Data.MySqlClient.MySqlException ex) { throw new Exception(ex.Message); } return ds; } } } /// /// 准备命令语句 /// /// Command命令 /// Connection对象 /// 是否是事务 /// 语句 /// 参数列表 private static void PrepareCommand(MySqlCommand cmd, MySqlConnection conn, MySqlTransaction trans, string cmdText, MySqlParameter[] cmdParms) { if (conn.State != ConnectionState.Open) conn.Open(); cmd.Connection = conn; cmd.CommandText = cmdText; if (trans != null) cmd.Transaction = trans; cmd.CommandType = CommandType.Text;//cmdType; if (cmdParms != null) { foreach (MySqlParameter parameter in cmdParms) { if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null)) { parameter.Value = DBNull.Value; } cmd.Parameters.Add(parameter); } } } #endregion #region 参数转换 /// /// 准备MysqlCommad参数 /// /// MySqlCommand cmd对象 /// MySqlConnection conn对象 /// 数据库事务 /// text or StoredProcedure /// 存储过程名 /// SqlCommand的参数 private static void PrepareMySqlCommand(MySql.Data.MySqlClient.MySqlCommand cmd, MySql.Data.MySqlClient.MySqlConnection conn, MySqlTransaction trans, CommandType cmdType, string cmdText, MySqlParameter[] cmdParms) { //连接状态是否打开 if (conn.State != ConnectionState.Open) conn.Open(); cmd.Connection = conn; cmd.CommandText = cmdText; //Transact-SQL 事务 if (trans != null) cmd.Transaction = trans; cmd.CommandType = cmdType; if (cmdParms != null) { foreach (MySqlParameter parm in cmdParms) cmd.Parameters.Add(parm); } } /// /// 放回一个MakeMySqlParameter /// /// 参数名字 /// 参数类型 /// 参数大小 /// 参数值 /// SQLiteParameter的值 public static MySqlParameter MakeMySqlParameter(string name, MySqlDbType type, int size, object value) { MySqlParameter parm = new MySqlParameter(name, type, size); parm.Value = value; return parm; } /// /// 创建MysqlParameter /// /// 字段名称 /// 数据类型 /// 字段值 /// 返回类型为MySqlParameter public static MySqlParameter MakeMySqlParameter(string name, MySqlDbType type, object value) { MySqlParameter parm = new MySqlParameter(name, type); parm.Value = value; return parm; } #endregion #region C#调用Mysql的存储过程--自修改 #region 简单存储过程,返回结果中第一行第一列的值,要求第一行第一列有返回 /// /// 简单存储过程,返回结果中第一行第一列的值,要求第一行第一列有返回 /// /// 存储过程名 /// public static int ExecuteProc(string ProcName) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { using (MySqlCommand cmd = new MySqlCommand(ProcName, connection)) { try { cmd.CommandType = CommandType.StoredProcedure; connection.Open();//int rows = int result = int.Parse(cmd.ExecuteScalar().ToString()); return result; } catch (MySql.Data.MySqlClient.MySqlException e) { connection.Close(); throw new Exception(e.Message); } } } } #endregion #region 执行带参数的存储过程 /// /// 执行带参数的存储过程 /// /// 存储过程名 /// 参数MySqlParameter[] cmdParms /// public static string ExecuteProc(string ProcName, params MySqlParameter[] cmdParms) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { using (MySqlCommand cmd = new MySqlCommand()) { try { cmd.CommandType = CommandType.StoredProcedure; //cmd.CommandText = ProcName; PrepareMySqlCommand(cmd, connection, null, CommandType.StoredProcedure, ProcName, cmdParms); // PrepareCommand(cmd, connection, null, ProcName, cmdParms); //connection.Open();//int rows = string result = cmd.ExecuteScalar().ToString(); return result; } catch (MySql.Data.MySqlClient.MySqlException e) { connection.Close(); throw new Exception(e.Message); } } } } #endregion #region 执行带参数的存储过程(返回DateSet) /// /// 执行带参数的存储过程 /// /// 存储过程名 /// 参数MySqlParameter[] cmdParms /// public static DataSet ExecuteProcDataset(string ProcName, params MySqlParameter[] cmdParms) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { MySqlCommand cmd = new MySqlCommand(); PrepareMySqlCommand(cmd, connection, null, CommandType.StoredProcedure, ProcName, cmdParms); using (MySqlDataAdapter da = new MySqlDataAdapter(cmd)) { DataSet ds = new DataSet(); try { da.Fill(ds, "ds"); cmd.Parameters.Clear(); } catch (MySql.Data.MySqlClient.MySqlException ex) { throw new Exception(ex.Message); } return ds; } } } public static DataSet ExecuteProcDataset(string ProcName) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { MySqlCommand cmd = new MySqlCommand(); PrepareMySqlCommand(cmd, connection, null, CommandType.StoredProcedure, ProcName, null); using (MySqlDataAdapter da = new MySqlDataAdapter(cmd)) { DataSet ds = new DataSet(); try { da.Fill(ds, "ds"); cmd.Parameters.Clear(); } catch (MySql.Data.MySqlClient.MySqlException ex) { throw new Exception(ex.Message); } return ds; } } } #endregion #endregion } }