Asp.Net操做MySql數據庫增刪改查,話很少說直接步入正題。git源碼地址:https://git.oschina.net/gxiaopan/NetMySql.git html
一、安裝MySQL數據庫系統,目前最新版本爲5.7.17,能夠到官網 http://dev.mysql.com/downloads/mysql/ 下載安裝,注意安裝選擇Microsoft Windows平臺;mysql
msi格式直接可視化安裝便可,zip格式是本身解壓,解壓縮以後其實MySQL就可使用了,可是要進行配置,git
配置環境變量很簡單:web
個人電腦->屬性->高級->環境變量sql
選擇PATH,在其後面添加: 你的mysql bin文件夾的路徑 (如:C:\Program Files\MySQL\MySQL Server 5.6\bin )數據庫
PATH=.......;C:\Program Files\MySQL\MySQL Server 5.6\bin (注意是追加,不是覆蓋)ide
配置完環境變量以後先別忙着啓動mysql,咱們還須要修改一下配置文件(若是沒有配置,以後啓動的時候就會出現圖中的錯誤哦!:錯誤2 系統找不到文件),mysql-5.6.1X默認的配置文件是在C:\Program Files\MySQL\MySQL Server 5.6\my-default.ini,或者本身創建一個my.ini文件,lua
在其中修改或添加配置(如圖): spa
[mysqld] .net
basedir=C:\Program Files\MySQL\MySQL Server 5.6(mysql所在目錄)
datadir=C:\Program Files\MySQL\MySQL Server 5.6\data (mysql所在目錄\data)
以管理員身份運行cmd(必定要用管理員身份運行,否則權限不夠),
輸入:cd C:\Program Files\MySQL\MySQL Server 5.6\bin 進入mysql的bin文件夾(無論有沒有配置過環境變量,也要進入bin文件夾,不然以後啓動服務仍然會報錯誤2)
輸入mysqld -install(若是不用管理員身份運行,將會由於權限不夠而出現錯誤:Install/Remove of the Service Denied!)
安裝成功
安裝成功後就要啓動服務了,繼續在cmd中輸入:net start mysql(如圖),服務啓動成功!
此時不少人會出現錯誤,請看注意:
注意:這個時候常常會出現錯誤2和錯誤1067。
若是出現「錯誤2 系統找不到文件」,檢查一下是否修改過配置文件或者是否進入在bin目錄下操做,若是配置文件修改正確而且進入了bin文件夾,須要先刪除mysql(輸入 mysqld -remove)再從新安裝(輸入 mysqld -install);
若是出現錯誤1067,那就是配置文件修改錯誤,確認一下配置文件是否正確。
服務啓動成功以後,就能夠登陸了,如圖,輸入mysql -u root -p(第一次登陸沒有密碼,直接按回車過),登陸成功!
二、引用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的引用,以下圖所示:
三、使用下面的代碼完成對數據庫的鏈接:
在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