首页 > 代码库 > C#的MySQL操作工具类
C#的MySQL操作工具类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.Data;
namespace ConsoleApplication1
{
class MySqlOperateTool
{
private const string serverIP = "localhost";//mysql服务器的IP地址
private const string serverPort = "3306";//mysql服务器的端口
private const string userName = "LGQ";//mysql服务器的用户名
private const string userPassword = "lgq";//mysql服务器的用户密码
/// <summary>
/// MySqlOperateTool工具类的测试方法(供使用MySqlOperateTool工具类的人员进行参考)
/// </summary>
public static void mySqlOperateToolTest() {
MySqlConnection dbConnection = MySqlOperateTool.getConnection("test");
if (dbConnection != null)
{
//创建一个事务
MySqlTransaction transaction = MySqlOperateTool.beginTransaction(dbConnection);
try
{
string sql = "insert into testTable values(1001,‘张三‘,‘男‘)";
MySqlOperateTool.executeNonQuery(sql, dbConnection);
sql = "insert into testTable values(1002,‘李四‘,‘女‘)";
MySqlOperateTool.executeNonQuery(sql, dbConnection);
////模拟异常
//int aa = 0;
//int bb = 10 / aa;
//提交事务
MySqlOperateTool.transactionCommit(transaction);
}
catch (Exception)
{
//回滚事务
MySqlOperateTool.transactionRollback(transaction);
}
MySqlOperateTool.closeConnection(dbConnection);
}
//MySqlConnection dbConnection = MySqlOperateTool.getConnection("test");
//if (dbConnection != null)
//{
// string sql = "select count(id) from testTable";
// object resultSetCnt = MySqlOperateTool.getSingleObject(sql, dbConnection);
// if (resultSetCnt != null)
// {
// System.Console.WriteLine("resultSetCnt:" + (long)resultSetCnt);
// }
// sql = "select * from testTable";
// MySqlDataReader dataReader = MySqlOperateTool.getDataReader(sql, dbConnection);
// if (dataReader!=null)
// {
// while (dataReader.Read())
// {
// int id = (int)dataReader["id"];
// string name = (string)dataReader["name"];
// string sex = (string)dataReader["sex"];
// System.Console.WriteLine("id:"+id+" name:"+name+" sex:"+sex);
// }
// }
// MySqlOperateTool.closeConnection(dbConnection);
//}
//MySqlConnection dbConnection = MySqlOperateTool.getConnection("test");
//if (dbConnection != null)
//{
// DataSet dataset = new DataSet();//定义一个DataSet
// string sql = "select * from testTable";
// bool resultFlag = MySqlOperateTool.dataAdappterDataSet(sql,dataset,"persons", dbConnection);
// if (resultFlag)
// {
// foreach (DataRow therow in dataset.Tables["persons"].Rows)
// {
// int id = (int)therow["id"];
// string name = (string)therow["name"];
// string sex = (string)therow["sex"];
// System.Console.WriteLine("id:" + id + " name:" + name + " sex:" + sex);
// }
// }
// MySqlOperateTool.closeConnection(dbConnection);
//}
//MySqlConnection dbConnection = MySqlOperateTool.getConnection("test");
//if (dbConnection != null)
//{
// DataSet dataset = new DataSet();//定义一个DataSet
// string sql = "select * from testTable";
// //获得一个空的用于更新的类对象
// MySqlCommandBuilder commandBuilder = MySqlOperateTool.dataAdappterDataSetUpdate(sql, dataset, "persons", dbConnection);
// if (commandBuilder!=null)
// {
// //更新数据库的内容(假设数据库中有两行以上的人员信息)
// dataset.Tables["persons"].Rows[0]["name"] = "天机小红";
// dataset.Tables["persons"].Rows[0]["sex"] = "女";
// dataset.Tables["persons"].Rows[1]["name"] = "小李分刀";
// dataset.Tables["persons"].Rows[1]["sex"] = "男";
// commandBuilder.DataAdapter.Update(dataset, "persons");
// }
// MySqlOperateTool.closeConnection(dbConnection);
//}
//MySqlConnection dbConnection = MySqlOperateTool.getConnection("test");
//if (dbConnection != null)
//{
// DataSet dataset = new DataSet();//定义一个DataSet
// string sql = "select * from testTable";
// //获得一个空的用于更新的类对象
// MySqlCommandBuilder commandBuilder = MySqlOperateTool.dataAdappterDataSetUpdate(sql, dataset, "persons", dbConnection);
// if (commandBuilder != null)
// {
// //向数据库中添加内容
// DataRow datarow = dataset.Tables["persons"].NewRow();//以此表的字段定义一个新的一行数据
// datarow["id"] = 1003;
// datarow["name"] = "张三";
// datarow["sex"] = "男";
// dataset.Tables["persons"].Rows.Add(datarow);
// datarow = dataset.Tables["persons"].NewRow();//以此表的字段定义一个新的一行数据
// datarow["id"] = 1004;
// datarow["name"] = "李四";
// datarow["sex"] = "女";
// dataset.Tables["persons"].Rows.Add(datarow);
// commandBuilder.DataAdapter.Update(dataset, "persons");
// }
// MySqlOperateTool.closeConnection(dbConnection);
//}
//MySqlConnection dbConnection = MySqlOperateTool.getConnection("test");
//if (dbConnection != null)
//{
// DataSet dataset = new DataSet();//定义一个DataSet
// string sql = "select * from testTable";
// //获得一个空的用于更新的类对象
// MySqlCommandBuilder commandBuilder = MySqlOperateTool.dataAdappterDataSetUpdate(sql, dataset, "persons", dbConnection);
// if (commandBuilder != null)
// {
// //从数据库中删除内容
// DataRow datarow = dataset.Tables["persons"].Rows[2];
// datarow.Delete();
// datarow = dataset.Tables["persons"].Rows[3];
// datarow.Delete();
// commandBuilder.DataAdapter.Update(dataset, "persons");
// }
// MySqlOperateTool.closeConnection(dbConnection);
//}
}
/// <summary>
/// 获取数据库连接对象
/// </summary>
/// <param name="dbFile">传入的数据库名</param>
/// <returns>返回值为null代表获取连接失败</returns>
public static MySqlConnection getConnection(string dbName)
{
MySqlConnection dbConnection = null;
if (string.IsNullOrEmpty(dbName))//如果传入的参数异常
{
return null;
}
string connectStr = "Data Source=" + serverIP + ";Port=" + serverPort + ";User ID=" + userName + ";Password=" + userPassword + ";Database=" + dbName + ";CharSet=utf8;";
try {
MySqlConnection connection = new MySqlConnection(connectStr);
connection.Open();
//获得mysql数据库连接对象成功
dbConnection = connection;
}catch(Exception){
System.Console.WriteLine("C#获得mysql数据库连接对象时产生了异常!");
}
return dbConnection;
}
/// <summary>
/// 创建一个事务,并且开始执行事务
/// </summary>
/// <param name="dbConnection">数据库连接对象</param>
/// <returns>返回为null代表创建事务失败</returns>
public static MySqlTransaction beginTransaction(MySqlConnection dbConnection)
{
MySqlTransaction transaction = null;
if (dbConnection == null)
{
return null;
}
try
{
transaction = dbConnection.BeginTransaction();//创建事务,并且开始执行事务
}
catch (Exception) {
Console.WriteLine("创建事务时产生了异常!");
}
return transaction;
}
/// <summary>
/// 提交事务
/// </summary>
/// <param name="transaction">与一个事务相关的对象</param>
public static void transactionCommit(MySqlTransaction transaction)
{
try
{
//提交事务
transaction.Commit();
}
catch (Exception)
{
Console.WriteLine("提交事务时产生了异常!");
}
}
/// <summary>
/// 回滚事务
/// </summary>
/// <param name="transaction">与一个事务相关的对象</param>
public static void transactionRollback(MySqlTransaction transaction)
{
try
{
//回滚事务
transaction.Rollback();
}
catch (Exception)
{
Console.WriteLine("回滚事务时产生了异常!");
}
}
/// <summary>
/// 关闭数据库的连接
/// </summary>
/// <param name="db_connection">数据库连接对象</param>
public static void closeConnection(MySqlConnection dbConnection)
{
//如果连接不为空
if (dbConnection != null)
{
try {
dbConnection.Close();
}catch(Exception){
System.Console.WriteLine("C#关闭mysql数据库连接对象时产生了异常!");
}
}
}
/// <summary>
/// 查询单个信息
/// </summary>
/// <param name="sql">sql查询语句</param>
/// <param name="db_connection">数据库连接对象</param>
/// <returns>
/// 如果返回值为null代表查询失败;
/// 此方法只能返回一个值,主要用于查行数,等其他用途(传入的参数均不能为空);
/// 返回 Object 类型的数据,执行查询,并返回查询所返回的结果集中第一行的第一列。忽略其他列或行;
/// </returns>
public static Object getSingleObject(string sql, MySqlConnection dbConnection)
{
Object result = null;
if (string.IsNullOrEmpty(sql) || dbConnection == null)//如果传入参数不合法
{
return null;
}
try
{
MySqlCommand command = new MySqlCommand(sql, dbConnection);//创建数据库执行命令语句对象
result = command.ExecuteScalar();//此命令只会返回一个值
}
catch (Exception)//如果sql命令执行失败
{
Console.WriteLine("sql查询语句不合法或者数据库连接对象异常!");
}
return result;//返回读到的值
}
/// <summary>
/// 执行sql语句
/// </summary>
/// <param name="sql">sql执行语句</param>
/// <param name="db_connection">数据库连接对象</param>
/// <returns>
/// 返回值为0代表sql命令执行后对数据库无任何影响,如果返回值大于0代表sql命令执行后对数据库产生了影响;
/// 此方法只能返回一个值(指令在数据库影响的行数),主要用于执行 insert、delete、alter操作;
/// </returns>
public static int executeNonQuery(string sql, MySqlConnection dbConnection)
{
//sql语句执行后影响的行数,初始化为0
int resultCnt = 0;
if (string.IsNullOrEmpty(sql) || dbConnection == null)//如果传入参数不合法
{
return 0;
}
try
{
MySqlCommand command = dbConnection.CreateCommand();//创建数据库执行命令语句对象
command.CommandText = sql;//执行相关的sql语句
resultCnt = command.ExecuteNonQuery();//此命令无查询功能
}
catch (Exception)//如果sql命令执行失败
{
Console.WriteLine("sql查询语句不合法或者数据库连接对象异常!");
}
return resultCnt;//返回影响的行数
}
/// <summary>
/// 查询多行信息
/// </summary>
/// <param name="sql">sql查询语句</param>
/// <param name="db_connection">数据库连接对象</param>
/// <returns>
/// 返回为null,代表查询失败,返回 MySqlDataReader 类型的数据,主要用于检索多行值;
/// 此方法只能返回 MySqlDataReader 类型的数据,只能一行一行的读数据;
/// </returns>
public static MySqlDataReader getDataReader(string sql, MySqlConnection dbConnection)
{
MySqlDataReader data_read = null;
if (string.IsNullOrEmpty(sql) || dbConnection == null)//如果传入参数不合法
{
return null;
}
try
{
MySqlCommand command = dbConnection.CreateCommand();//创建数据库执行命令语句对象
command.CommandText = sql;//执行相关的sql语句
data_read = command.ExecuteReader();//读取数据库中的数据
}
catch (Exception)//如果sql命令执行失败
{
Console.WriteLine("sql查询语句不合法或者数据库连接对象异常!");
}
return data_read;//返回读到的数据
}
/// <summary>
/// 此方法是向传入的 dataset 中填入数据,“不支持更新功能”
/// </summary>
/// <param name="sql">sql查询语句</param>
/// <param name="dataset">用于存储查询信息的数据集缓存区</param>
/// <param name="table_name">是dataset要缓存查询信息的DataTble名称</param>
/// <param name="db_connection">数据库连接对象</param>
/// <returns>查询成功返回true,失败返回false</returns>
public static bool dataAdappterDataSet(string sql, DataSet dataset, string table_name, MySqlConnection dbConnection)
{
//初始化查询失败
bool result = false;
if (string.IsNullOrEmpty(sql) || dataset == null || string.IsNullOrEmpty(table_name) || dbConnection==null)
{
return false;
}
try
{
//定义将数据库的数据匹配到DataSet的适配器对象
MySqlDataAdapter data_adappter = new MySqlDataAdapter(sql, dbConnection);
data_adappter.Fill(dataset, table_name);
result = true;//查询成功
}
catch (Exception)//如果sql命令执行失败
{
Console.WriteLine("sql查询语句不合法或者数据库连接对象异常!");
}
return result;//返回查询结果
}
/// <summary>
/// 此方法是向传入的 dataset 中填入数据,“支持更新功能”,执行更新之前不能断开与数据库的连接
/// </summary>
/// <param name="sql">sql查询语句</param>
/// <param name="dataset">用于存储查询信息的数据集缓存区</param>
/// <param name="table_name">是dataset要缓存查询信息的DataTble名称</param>
/// <param name="db_connection">数据库连接对象</param>
/// <returns>返回一个 MySqlCommandBuilder 对象,可以用来进行更新操作,将内存dataset中改变的数据同步到数据库中</returns>
public static MySqlCommandBuilder dataAdappterDataSetUpdate(string sql, DataSet dataset, string table_name, MySqlConnection dbConnection)
{
MySqlCommandBuilder commandBuilder = null;
if (string.IsNullOrEmpty(sql) || dataset == null || string.IsNullOrEmpty(table_name) || dbConnection == null)
{
return null;
}
try
{
//定义将数据库的数据匹配到DataSet的适配器对象
MySqlDataAdapter data_adappter = new MySqlDataAdapter(sql, dbConnection);
MySqlCommandBuilder builder = new MySqlCommandBuilder(data_adappter);
data_adappter.Fill(dataset, table_name);
commandBuilder = builder;//查询成功
}
catch (Exception)//如果sql命令执行失败
{
Console.WriteLine("sql查询语句不合法或者数据库连接对象异常!");
}
return commandBuilder;//查询结束,返回commandBuilder
}
}
}
内容来自:越康体育
C#的MySQL操作工具类