C# 连接 MySQL 数据库
目录
一、需求
二、新建 C# 项目
三、MySQL数据库
四、MySqlHelper
五、测试
一、需求
C# 使用 MySQL 数据库的情况还是比较少的,大部分使用 Windows 平台一般使用 SQL Server,在两年前我买过100元一年的学生服务器,当时也是买着玩的,装 MySQL 数据库使用起来就非常卡,也不知道为什么,但 SQL Server 操作起来不但不卡,还非常的流畅,但是 SQL Server 安装起来比较麻烦,卸载也容易出问题,尤其是盗版系统,我在工作中,也出现了几次 SQL Server 卸载不了的事,我自己电脑用的正版Win10系统,从没出现这种事。MySQL 和 SQL Server 各有自己的优点,如果非要使用 MySQL,也是可以的,下面就会介绍 C# 如何去调用 MySQL。
二、新建 C# 项目
新建一个控制台项目,取名 CSharpConnectMySQL
这里我使用的不使用顶级语句
项目创建完成后,如下
namespace CSharpConnectMySQL
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}
三、MySQL数据库
MySQL 的安装,可以在百度搜一下,这里就不演示了
下面不搞复杂的流程,随便弄点数据,就以 shop 数据库 中的 goods_type 来演示好了。
各位可以自己动手操作一下,数据库和表不一定和我的一样,在后面的 sql 语句中,自己改下就好了。
四、MySqlHelper
在使用之前,先安装 MySql.Data 插件
接着安装 System.Data.SqlClient
这样就安装完成了,接下来就是代码了
MySqlHelper.cs
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharpConnectMySQL
{
public class MySqlHelper
{
private static string connstr = "server=127.0.0.1;database=shop;username=root;password=123456;";
#region 执行查询语句,返回MySqlDataReader
/// <summary>
/// 执行查询语句,返回MySqlDataReader
/// </summary>
/// <param name="sqlString"></param>
/// <returns></returns>
public static MySqlDataReader ExecuteReader(string sqlString)
{
MySqlConnection connection = new MySqlConnection(connstr);
MySqlCommand cmd = new MySqlCommand(sqlString, connection);
MySqlDataReader myReader = null;
try
{
connection.Open();
myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return myReader;
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
throw new Exception(e.Message);
}
finally
{
if (myReader == null)
{
cmd.Dispose();
connection.Close();
}
}
}
#endregion
#region 执行带参数的查询语句,返回 MySqlDataReader
/// <summary>
/// 执行带参数的查询语句,返回MySqlDataReader
/// </summary>
/// <param name="sqlString"></param>
/// <param name="cmdParms"></param>
/// <returns></returns>
public static MySqlDataReader ExecuteReader(string sqlString, params MySqlParameter[] cmdParms)
{
MySqlConnection connection = new MySqlConnection(connstr);
MySqlCommand cmd = new MySqlCommand();
MySqlDataReader myReader = null;
try
{
PrepareCommand(cmd, connection, null, sqlString, cmdParms);
myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return myReader;
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
throw new Exception(e.Message);
}
finally
{
if (myReader == null)
{
cmd.Dispose();
connection.Close();
}
}
}
#endregion
#region 执行sql语句,返回执行行数
/// <summary>
/// 执行sql语句,返回执行行数
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static int ExecuteSql(string sql)
{
using (MySqlConnection conn = new MySqlConnection(connstr))
{
using (MySqlCommand cmd = new MySqlCommand(sql, conn))
{
try
{
conn.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
conn.Close();
//throw e;
Console.WriteLine(e.Message);
}
finally
{
cmd.Dispose();
conn.Close();
}
}
}
return -1;
}
#endregion
#region 执行带参数的sql语句,并返回执行行数
/// <summary>
/// 执行带参数的sql语句,并返回执行行数
/// </summary>
/// <param name="sqlString"></param>
/// <param name="cmdParms"></param>
/// <returns></returns>
public static int ExecuteSql(string sqlString, params MySqlParameter[] cmdParms)
{
using (MySqlConnection connection = new MySqlConnection(connstr))
{
using (MySqlCommand cmd = new MySqlCommand())
{
try
{
PrepareCommand(cmd, connection, null, sqlString, cmdParms);
int rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return rows;
}
catch (System.Data.SqlClient.SqlException E)
{
throw new Exception(E.Message);
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
}
#endregion
#region 执行查询语句,返回DataSet
/// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static DataSet GetDataSet(string sql)
{
using (MySqlConnection conn = new MySqlConnection(connstr))
{
DataSet ds = new DataSet();
try
{
conn.Open();
MySqlDataAdapter DataAdapter = new MySqlDataAdapter(sql, conn);
DataAdapter.Fill(ds);
}
catch (Exception ex)
{
//throw ex;
Console.WriteLine(ex.Message);
}
finally
{
conn.Close();
}
return ds;
}
}
#endregion
#region 执行带参数的查询语句,返回DataSet
/// <summary>
/// 执行带参数的查询语句,返回DataSet
/// </summary>
/// <param name="sqlString"></param>
/// <param name="cmdParms"></param>
/// <returns></returns>
public static DataSet GetDataSet(string sqlString, params MySqlParameter[] cmdParms)
{
using (MySqlConnection connection = new MySqlConnection(connstr))
{
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 (System.Data.SqlClient.SqlException ex)
{
throw new Exception(ex.Message);
}
finally
{
cmd.Dispose();
connection.Close();
}
return ds;
}
}
}
#endregion
#region 执行带参数的sql语句,并返回 object
/// <summary>
/// 执行带参数的sql语句,并返回object
/// </summary>
/// <param name="sqlString"></param>
/// <param name="cmdParms"></param>
/// <returns></returns>
public static object GetSingle(string sqlString, params MySqlParameter[] cmdParms)
{
using (MySqlConnection connection = new MySqlConnection(connstr))
{
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 (System.Data.SqlClient.SqlException e)
{
throw new Exception(e.Message);
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
}
#endregion
/// <summary>
/// 执行存储过程,返回数据集
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>DataSet</returns>
public static DataSet RunProcedureForDataSet(string storedProcName, IDataParameter[] parameters)
{
using (MySqlConnection connection = new MySqlConnection(connstr))
{
DataSet dataSet = new DataSet();
connection.Open();
MySqlDataAdapter sqlDA = new MySqlDataAdapter();
sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
sqlDA.Fill(dataSet);
connection.Close();
return dataSet;
}
}
/// <summary>
/// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值)
/// </summary>
/// <param name="connection">数据库连接</param>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>SqlCommand</returns>
private static MySqlCommand BuildQueryCommand(MySqlConnection connection, string storedProcName,
IDataParameter[] parameters)
{
MySqlCommand command = new MySqlCommand(storedProcName, connection);
command.CommandType = CommandType.StoredProcedure;
foreach (MySqlParameter parameter in parameters)
{
command.Parameters.Add(parameter);
}
return command;
}
#region 装载MySqlCommand对象
/// <summary>
/// 装载MySqlCommand对象
/// </summary>
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 parm in cmdParms)
{
cmd.Parameters.Add(parm);
}
}
}
#endregion
}
}
connstr 中的配置,根据个人的设置来,也可以写配置文件中。
MySqlHelper 代码基本功能都有,代码不是我写的,我也是复制别人的
五、测试
代码
using System.Data;
namespace CSharpConnectMySQL
{
internal class Program
{
static void Main(string[] args)
{
string sql = "SELECT * FROM goods_type";
DataSet dataSet = MySqlHelper.GetDataSet(sql);
DataTable dt = dataSet.Tables[0];
if(dt.Rows.Count > 0)
{
//打印所有列名
string columnName = string.Empty;
for (int i = 0; i < dt.Columns.Count; i++)
{
columnName += dt.Columns[i].ColumnName + " | ";
}
Console.WriteLine(columnName);
Console.WriteLine("-------------------------");
//打印每一行的数据
foreach (DataRow row in dt.Rows)
{
string columnStr = string.Empty;
foreach (DataColumn column in dt.Columns)
{
columnStr += row[column] + " | ";
}
Console.WriteLine(columnStr);
}
}
Console.ReadKey();
}
}
}
运行:
这样就 O拉个K
end