博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
MysqlHelper类
阅读量:6047 次
发布时间:2019-06-20

本文共 12951 字,大约阅读时间需要 43 分钟。

连接方式:server=localhost;port=3306;userid=root;password=123456789;database=mysql;persist security info=true;charset=utf8 using System;using System;using System.Collections;using System.Collections.Specialized;using System.Data;using MySql.Data.MySqlClient;using System.Configuration;using System.Data.Common;using System.Collections.Generic;using System.Text.RegularExpressions;namespace ConsolePractice{    public static class MysqlHelper    {        //数据库连接字符串(web.config来配置),可以动态更改connectionString支持多数据库.         // public static string connectionString = ConfigurationManager.ConnectionStrings["ConnDB"].ConnectionString;         public static string connectionString = ConfigurationManager.AppSettings["MySQL"];        //public string m = ConfigurationManager.AppSettings["MySQL"];         //public MysqlHelper() { }        #region ExecuteNonQuery        //执行SQL语句,返回影响的记录数         ///          /// 执行SQL语句,返回影响的记录数         ///          /// SQL语句         /// 
影响的记录数
public static int ExecuteNonQuery(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; } } } } /// /// 执行SQL语句,返回影响的记录数 /// /// SQL语句 ///
影响的记录数
public static int ExecuteNonQuery(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语句,实现数据库事务。 /// /// 多条SQL语句 public static bool ExecuteNoQueryTran(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 { for (int n = 0; n < SQLStringList.Count; n++) { string strsql = SQLStringList[n]; if (strsql.Trim().Length > 1) { cmd.CommandText = strsql; PrepareCommand(cmd, conn, tx, strsql, null); cmd.ExecuteNonQuery(); } } cmd.ExecuteNonQuery(); tx.Commit(); return true; } catch { tx.Rollback(); return false; } } } #endregion #region ExecuteScalar ///
/// 执行一条计算查询结果语句,返回查询结果(object)。 /// ///
计算查询结果语句 ///
查询结果(object)
public static object ExecuteScalar(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; } } } } ///
/// 执行一条计算查询结果语句,返回查询结果(object)。 /// ///
计算查询结果语句 ///
查询结果(object)
public static object ExecuteScalar(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; } } } } #endregion #region ExecuteReader ///
/// 执行查询语句,返回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; } } ///
/// 执行查询语句,返回MySqlDataReader ( 注意:调用该方法后,一定要对MySqlDataReader进行Close ) /// ///
查询语句 ///
MySqlDataReader
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(); // } } #endregion #region ExecuteDataTable ///
/// 执行查询语句,返回DataTable /// ///
查询语句 ///
DataTable
public static DataTable ExecuteDataTable(string SQLString) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection); command.Fill(ds, "ds"); } catch (MySql.Data.MySqlClient.MySqlException ex) { throw new Exception(ex.Message); } return ds.Tables[0]; } } ///
/// 执行查询语句,返回DataSet /// ///
查询语句 ///
DataTable
public static DataTable ExecuteDataTable(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.Tables[0]; } } } //获取起始页码和结束页码 public static DataTable ExecuteDataTable(string cmdText, int startResord, int maxRecord) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); MySqlDataAdapter command = new MySqlDataAdapter(cmdText, connection); command.Fill(ds, startResord, maxRecord, "ds"); } catch (MySql.Data.MySqlClient.MySqlException ex) { throw new Exception(ex.Message); } return ds.Tables[0]; } } #endregion ///
/// 获取分页数据 在不用存储过程情况下 /// ///
总记录条数 ///
选择的列逗号隔开,支持top num ///
表名字 ///
条件字符 必须前加 and ///
排序 例如 ID ///
当前索引页 ///
每页记录数 ///
public static DataTable getPager(out int recordCount, string selectList, string tableName, string whereStr, string orderExpression, int pageIdex, int pageSize) { int rows = 0; DataTable dt = new DataTable(); MatchCollection matchs = Regex.Matches(selectList, @"top\s+\d{1,}", RegexOptions.IgnoreCase);//含有top string sqlStr = sqlStr = string.Format("select {0} from {1} where 1=1 {2}", selectList, tableName, whereStr); if (!string.IsNullOrEmpty(orderExpression)) { sqlStr += string.Format(" Order by {0}", orderExpression); } if (matchs.Count > 0) //含有top的时候 { DataTable dtTemp = ExecuteDataTable(sqlStr); rows = dtTemp.Rows.Count; } else //不含有top的时候 { string sqlCount = string.Format("select count(*) from {0} where 1=1 {1} ", tableName, whereStr); //获取行数 object obj = ExecuteScalar(sqlCount); if (obj != null) { rows = Convert.ToInt32(obj); } } dt = ExecuteDataTable(sqlStr, (pageIdex - 1) * pageSize, pageSize); recordCount = rows; return dt; } #region 创建command 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 }}

 

转载于:https://www.cnblogs.com/ChineseMoonGod/p/5152807.html

你可能感兴趣的文章
浅析NopCommerce的多语言方案
查看>>
设计模式之简单工厂模式
查看>>
C++中变量的持续性、链接性和作用域详解
查看>>
2017 4月5日上午
查看>>
第一阶段冲刺报告(一)
查看>>
使用crontab调度任务
查看>>
【转载】SQL经验小记
查看>>
zookeeper集群搭建 docker+zk集群搭建
查看>>
Vue2.5笔记:Vue的实例与生命周期
查看>>
论JVM爆炸的几种姿势及自救方法
查看>>
联合体、结构体简析
查看>>
使用throw让服务器端与客户端进行数据交互[Java]
查看>>
java反射与代理
查看>>
深度分析Java的ClassLoader机制(源码级别)
查看>>
微服务架构选Java还是选Go - 多用户负载测试
查看>>
我的友情链接
查看>>
69、iSCSI共享存储配置实战
查看>>
文本编程
查看>>
乔布斯走了。你还期待苹果吗?
查看>>
优先级
查看>>