1. 首先需要安裝mysql,
下載地址: http://www.jb51.net/softs/2193.html 或者去mysql.com官網都可以,一路next,安裝好後,有個簡單配置,提示有個設置登錄密碼和服務名稱,
默認localhost,用戶名root,密碼自己設置。
2. 安裝了mysql數據庫後,需要一個管理工具,就像sqlserver的SQL Server Management Studio一樣,推薦使用Navicat for MySQL,
下載地址:http://www.jb51.net/database/2223.html,安裝後,打開界面如下圖
確定後,右鍵新建的連接名字,就可以建數據庫,建表了。字段類型和sqlserver基本一致。
3. Asp.net連接mysql 不推薦使用ODBC,推薦是用mysql官網提供的組件動)MySQL.Data.Dll,官網地址,
http://dev.mysql.com/downloads/connector/net/5.1.html;可能需要簡單的注冊下用戶,看好版本,如果嫌棄麻煩可以直接下載一個相應版本的MySQL.Data.Dll ,放入bin下,增加引用即可
4. 我自己寫的一個簡單MysqlHelper.cs類,操作和sqlserver 很相似。有了這個類,你就知道怎麼用了,很簡單
代碼如下
復制代碼 代碼如下:
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
}
}
5. 需要注意的地方有如下幾點
1)在sqlserver中參數化sql語句是用“@”符號,在mysql裡面需要是用?號,切記,切記.
2 )還有就是sqlserver中刪除表可以這樣寫delete news where ID=12,但是在mysql裡面 是delete from news where ID=12,收了from報錯
3 )我在使用過程中遇到了中文亂碼,網上大部分解決辦法是把表的設置成utf-8字符集。以及 C:\Program Files\MySQL\MySQL Server 5.1路徑下my.ini 打開找到兩處
default-character-set 都設置成=utf8,但是我的還是亂碼,最後
6.以上是我的個人總結,有可能很膚淺,不要見笑,有問題共同解決,謝謝~