连接方式: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语句,返回影响的记录数
/// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
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;
}
}
}
}
/// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
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语句,实现数据库事务。
/// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">多条SQL语句</param>
public static bool ExecuteNoQueryTran(List<String> 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 = ; n < SQLStringList.Count; n++)
{
string strsql = SQLStringList[n];
if (strsql.Trim().Length > )
{
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
/// <summary>
/// 执行一条计算查询结果语句,返回查询结果(object)。
/// </summary>
/// <param name="SQLString">计算查询结果语句</param>
/// <returns>查询结果(object)</returns>
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;
}
}
}
}
/// <summary>
/// 执行一条计算查询结果语句,返回查询结果(object)。
/// </summary>
/// <param name="SQLString">计算查询结果语句</param>
/// <returns>查询结果(object)</returns>
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
/// <summary>
/// 执行查询语句,返回MySqlDataReader ( 注意:调用该方法后,一定要对MySqlDataReader进行Close )
/// </summary>
/// <param name="strSQL">查询语句</param>
/// <returns>MySqlDataReader</returns>
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;
}
}
/// <summary>
/// 执行查询语句,返回MySqlDataReader ( 注意:调用该方法后,一定要对MySqlDataReader进行Close )
/// </summary>
/// <param name="strSQL">查询语句</param>
/// <returns>MySqlDataReader</returns>
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
/// <summary>
/// 执行查询语句,返回DataTable
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataTable</returns>
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[];
}
}
/// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataTable</returns>
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[];
}
}
}
//获取起始页码和结束页码
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[];
}
}
#endregion
/// <summary>
/// 获取分页数据 在不用存储过程情况下
/// </summary>
/// <param name="recordCount">总记录条数</param>
/// <param name="selectList">选择的列逗号隔开,支持top num</param>
/// <param name="tableName">表名字</param>
/// <param name="whereStr">条件字符 必须前加 and</param>
/// <param name="orderExpression">排序 例如 ID</param>
/// <param name="pageIdex">当前索引页</param>
/// <param name="pageSize">每页记录数</param>
/// <returns></returns>
public static DataTable getPager(out int recordCount, string selectList, string tableName, string whereStr, string orderExpression, int pageIdex, int pageSize)
{
int rows = ;
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 > ) //含有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 - ) * 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
}
}

MysqlHelper类的更多相关文章

  1. PHP简单封装MysqlHelper类

    MysqlHelper.class.php 1: <?php 2:  3: /** 4: * Mysql数据帮助类 5: */ 6: class MysqlHelper 7: { 8: func ...

  2. [转]MySQLHelper类

    本文转自:http://de.cel.blog.163.com/blog/static/5145123620110181003903/ 类似于SQLHelper,只是这里引用的是MySql.Data类 ...

  3. 用于Mysql操作的MySqlHelper类

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Te ...

  4. C# 基于MySQL的数据层基类(MySQLHelper)

    这里介绍下比较简单的方式,引用MySql.Data.dll然后添加一个MySqlHelper类来对MySql数据库进行访问和操作. 1.将MySql.Data.dll引用到你的项目中 下载地址:MyS ...

  5. 在.NET连接MySQL以及封装好的MySQLHelper.cs

    1.首先上MySQL网站下驱动:http://www.mysql.com/products/connector/ 2.安装下载的安装包 3.我们在Visual Studio里创建一个Web Appli ...

  6. Java类的继承与多态特性-入门笔记

    相信对于继承和多态的概念性我就不在怎么解释啦!不管你是.Net还是Java面向对象编程都是比不缺少一堂课~~Net如此Java亦也有同样的思想成分包含其中. 继承,多态,封装是Java面向对象的3大特 ...

  7. java操作MySQL数据库(插入、删除、修改、查询、获取所有行数)

    插播一段广告哈:我之前共享了两个自己写的小应用,见这篇博客百度地图开发的两个应用源码共享(Android版),没 想到有人找我来做毕设了,年前交付,时间不是很紧,大概了解了下就接下了,主要用到的就是和 ...

  8. C# vs MySql

    MySqlHelper类 /// <summary> ///MySql操作类 /// </summary> public abstract class MySqlHelper ...

  9. .Net中如何使用MySql连接池

    提供一份官方的译文.翻译也挺辛苦的!! 6.4 Using Connector/Net with Connection Pooling 6.4在Connector/Net中使用连接池 The Conn ...

随机推荐

  1. iOS - 数组与字典(NSArray & NSDictionary)

    1. 数组的常用处理方式 //--------------------不可变数组 //1.数组的创建 NSString *s1 = @"zhangsan"; NSString *s ...

  2. (转)Mysql数据库读写分离配置

    环境模拟 实现读写分离 减轻数据库的负荷 主服务器 master 10.0.0.12从服务器 slave 10.0.0.66 ------------------------------------- ...

  3. (转)实战Memcached缓存系统(3)Memcached配置参数初解

    一.基本参数 在我们第一次安装Memcached时,一般都是用过这个命令: memcached -m 512 -u root -d -l 127.0.0.1 -p 11211 我们先来解释这几个参数的 ...

  4. css笔记——inline-block以及空白字符处理

    html <html> <head> <meta http-equiv="Content-Type" content="text/html; ...

  5. JAVA:避免重复的创建对象

    在实际开发中,重复使用同一个对象要比每次需要的时候就创建一个对象要好的多: 作为一个比较极端的反面例子,看下面这个语句: String s = new String("haha") ...

  6. [zz] 使用ssh公钥密钥自动登陆linux服务器

    目录 .生成密匙对 .拷贝公匙到远程机 .启动登陆代理 这种方法处理后每次需要运行命令:ssh-add ~/.ssh/id_dsa 作为一名 linux 管理员,在多台 Linux 服务器上登陆进行远 ...

  7. Qt学习总结-ui篇(二)

    qccs定义圆角   border-radius:10px; 如果想给特定位置定义圆角,如: 左上角:border-left-top-radius:10px; 右下角色:border-right-bo ...

  8. 分享一个难得的YiBo微博客户端应用源码Android版

    今天给大家分享一款,YiBo微博客户端应用源码,这是一款专为Android用户打造的聚合型微博客户端,完美支持新浪微博.腾讯微博.搜狐微博.网易微博和饭否五个微博平台,界面清爽,使用简单轻巧,支持多账 ...

  9. Android:ListView之ViewHolder

    前言 在开发Android应用过程中经常要与列表展示打交道,比如Listview.在使用过程中如果不能正确的进行细节处理那么对性能还是有很大的损耗的. Listview展示内容是通过一个Adapter ...

  10. Couchbase上发布的关于NoSQL的技术论文

    Couchbase是CouchDB与Membase两个NoSQL数据库相结合的产物,本文推荐的是Couchbase官方发表的一篇论文,命名为<NoSQL Database Technology& ...