C#——》Web Api 操作MySQL数据库公共类:MySql.Data
使用MySql.Data 连接mysql 数据库,需先引用MySql.Data ,用过MySql.Data.dll操作Mysql数据库。
1,在工具-Nuget包管理器-管理解决方案的Nuget程序包——安装MySql.data.dll
2,使用 MySqlConnection连接数据库,在使用MySqlCommand设置执行sql语句,执行类别,使用参数。
using System;
using System.Configuration;
using MySql.Data.MySqlClient;
using System.Data;
namespace Webapi.Data
{
public static class DBHelper
{
private static MySqlConnection con = null;
//获取配置文件中的数据库地址
private static string connection = ConfigurationManager.ConnectionStrings["smallprocedures"].ConnectionString;
/// <summary>
/// 开启/关闭数据库连接
/// </summary>
public static void Connection()
{
try
{
if (con != null)
con.Clone();
else
{
con = new MySqlConnection(connection);
con.Open();
}
}
catch (Exception e)
{
//连接失败
}
}
/// <summary>
/// 查询
/// </summary>
/// <param name="sql">sql语句</param>
/// <returns></returns>
public static DataSet Select(string sql)
{
DataSet ds = new DataSet();
try
{
Connection();//开启
MySqlCommand com = new MySqlCommand(sql, con);
com.CommandType = CommandType.Text;//执行sql语句
MySqlDataAdapter db = new MySqlDataAdapter(com);
db.Fill(ds);//读取数据
}
catch (Exception e)
{
}
finally
{
Connection();//关闭
}
return ds;
}
/// <summary>
/// 查询(存储过程)
/// </summary>
/// <param name="procedureName">存储过程名称</param>
/// <param name="sqlParameter">参数</param>
/// <returns></returns>
public static DataSet Select_Procedure(string procedureName, MySqlParameter [] sqlParameter)
{
DataSet ds = new DataSet();
Connection();
MySqlCommand com = new MySqlCommand(procedureName, con);
com.CommandType = CommandType.StoredProcedure;//执行存储过程
try
{
if (sqlParameter != null)
{
for (int i = 0; i < sqlParameter.Length; i++)
com.Parameters.Add(sqlParameter[i]);
}
using (MySqlDataAdapter db = new MySqlDataAdapter(com))
db.Fill(ds);
}
catch (Exception e)
{
com.Parameters.Clear();
}
finally
{
Connection();
}
return ds;
}
/// <summary>
/// 增删改
/// </summary>
/// <param name="sql">sql语句</param>
/// <returns></returns>
public static bool Update(string sql)
{
Connection();
int num = 0;
MySqlCommand com = new MySqlCommand(sql, con);
MySqlTransaction sqlTransaction = com.Transaction;//创建事务
try
{
num= com.ExecuteNonQuery();
}
catch (Exception)
{
//异常处理
}
finally
{
if (num > 0)
sqlTransaction.Commit();//提交
else
sqlTransaction.Rollback();//回滚
Connection();
}
return false;
}
}
}