Asp.Net操作MySql数据库增删改查

Asp.Net操作MySql数据库增删改查,话不多说直接步入正题。git源码地址:https://git.oschina.net/gxiaopan/NetMySql.git 

1、安装MySQL数据库系统,目前最新版本为5.7.17,可以到官网 http://dev.mysql.com/downloads/mysql/ 下载安装,注意安装选择Microsoft Windows平台;

msi格式直接可视化安装即可,zip格式是自己解压,解压缩之后其实MySQL就可以使用了,但是要进行配置,

配置环境变量很简单:

我的电脑->属性->高级->环境变量

选择PATH,在其后面添加: 你的mysql bin文件夹的路径 (如:C:\Program Files\MySQL\MySQL Server 5.6\bin )

PATH=.......;C:\Program Files\MySQL\MySQL Server 5.6\bin (注意是追加,不是覆盖)

 

配置完环境变量之后先别忙着启动mysql,我们还需要修改一下配置文件(如果没有配置,之后启动的时候就会出现图中的错误哦!:错误2 系统找不到文件),mysql-5.6.1X默认的配置文件是在C:\Program Files\MySQL\MySQL Server 5.6\my-default.ini,或者自己建立一个my.ini文件,

在其中修改或添加配置(如图): 

[mysqld] 

basedir=C:\Program Files\MySQL\MySQL Server 5.6(mysql所在目录) 

datadir=C:\Program Files\MySQL\MySQL Server 5.6\data (mysql所在目录\data)


  1. MySQL 5.6 for Windows 解压缩版配置安装
    MySQL 5.6 for Windows 解压缩版配置安装
  2.  

    以管理员身份运行cmd(一定要用管理员身份运行,不然权限不够),

    输入:cd C:\Program Files\MySQL\MySQL Server 5.6\bin 进入mysql的bin文件夹(不管有没有配置过环境变量,也要进入bin文件夹,否则之后启动服务仍然会报错误2)

    输入mysqld -install(如果不用管理员身份运行,将会因为权限不够而出现错误:Install/Remove of the Service Denied!) 

    安装成功

    MySQL 5.6 for Windows 解压缩版配置安装
    MySQL 5.6 for Windows 解压缩版配置安装
  3.  

    安装成功后就要启动服务了,继续在cmd中输入:net start mysql(如图),服务启动成功!

    此时很多人会出现错误,请看注意:

    注意:这个时候经常会出现错误2和错误1067。

    如果出现“错误2 系统找不到文件”,检查一下是否修改过配置文件或者是否进入在bin目录下操作,如果配置文件修改正确并且进入了bin文件夹,需要先删除mysql(输入 mysqld -remove)再重新安装(输入 mysqld -install);

    如果出现错误1067,那就是配置文件修改错误,确认一下配置文件是否正确。

    MySQL 5.6 for Windows 解压缩版配置安装
  4.  

    服务启动成功之后,就可以登录了,如图,输入mysql -u root -p(第一次登录没有密码,直接按回车过),登录成功!

    MySQL 5.6 for Windows 解压缩版配置安装
  5.  

2、引用MySQL connector/Net组件,该组件在安装MySQL安装目录内,比如本人电脑上的目录是:

D:\Program Files (x86)\MySQL\Connector NET 6.7.4\Assemblies\v4.5\MySQL.Data.dll

或者到官网上下载 http://dev.mysql.com/downloads/connector/net/ 最新版本的MySQL connector/Net组件

需要说明的是,如果在正常安装MySQL数据库后,又更新了MySQL Connector/Net组件,则会出现版本不同的问题,这需要将ASP.NET中machine.config里面关于MySQL引用 MySQL Connector/Net组件版本的语句注释掉即可;

引用 MySQL connector/Net组件的办法是在ASP.NET项目引用中添加地MySQL.Data.dll的引用,如下图所示:

3、使用下面的代码完成对数据库的连接:  

 在web.config中配置连接字符串完成对MySQL数据库的连接

 <connectionStrings>

   <add name="DBConnection"  connectionString="server=localhost;user id=root;password=123456;database=MySqlDatabaseName; pooling=true;" providerName="MySql.Data.MySqlClient/>

</connectionStrings>


编写C#操作
MysqlHelper类:
MysqlHelper类 
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 LOAF.DAL 
{ 
public 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 = 0; n < SQLStringList.Count; n++) 
{ 
string strsql = SQLStringList[n]; 
if (strsql.Trim().Length > 1) 
{ 
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[0]; 
} 
} 
/// <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[0]; 
} 
} 
} 
//获取起始页码和结束页码 
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[0]; 
} 
} 
#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 = 0; 
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 > 0) //含有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-1)*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 
} 
} 
 git源码地址:https://git.oschina.net/gxiaopan/NetMySql.git

 

转载于:https://www.cnblogs.com/Gxiaopan/p/6292556.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值