C#——》WebApi操作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();
sqltransaction什么意思 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;
}
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论