/**
* 類說明:對(duì)MYSQL數(shù)據(jù)庫(kù)的操作類
*/
using System;
using System.Data;
using MySql.Data.MySqlClient;
namespace Niunan.BYLW.Utility
{
/// summary>對(duì)MYSQL數(shù)據(jù)庫(kù)的操作類
///
/// /summary>
public class MYSQLHelper
{
private MySqlConnection conn = null;
private MySqlCommand cmd = null;
private MySqlDataReader sdr = null;
public MYSQLHelper()
{
//string connStr = WebConfigurationManager.ConnectionStrings["connStr"].ToString();
string connStr = "server=localhost;database=test;uid=root;pwd=123456;charset=utf8";
conn = new MySqlConnection(connStr);
}
/// summary>創(chuàng)建Command對(duì)象
///
/// /summary>
/// param name="sql">SQL語(yǔ)句/param>
public void CreateCommand(string sql)
{
conn.Open();
cmd = new MySqlCommand(sql, conn);
}
/// summary>添加參數(shù)
///
/// /summary>
/// param name="paramName">參數(shù)名稱/param>
/// param name="value">值/param>
public void AddParameter(string paramName, object value)
{
cmd.Parameters.Add(new MySqlParameter(paramName, value));
}
/// summary>執(zhí)行不帶參數(shù)的增刪改SQL語(yǔ)句
///
/// /summary>
/// param name="cmdText">增刪改SQL語(yǔ)句/param>
/// param name="ct">命令類型/param>
/// returns>/returns>
public bool ExecuteNonQuery()
{
int res;
try
{
res = cmd.ExecuteNonQuery();
if (res > 0)
{
return true;
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
return false;
}
/// summary>執(zhí)行查詢SQL語(yǔ)句
///
/// /summary>
/// param name="cmdText">查詢SQL語(yǔ)句/param>
/// returns>/returns>
public DataTable ExecuteQuery()
{
DataTable dt = new DataTable();
using (sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
dt.Load(sdr);
}
return dt;
}
/// summary>返回查詢SQL語(yǔ)句查詢出的結(jié)果的第一行第一列的值
///
/// /summary>
/// returns>/returns>
public string ExecuteScalar()
{
string res = "";
try
{
object obj = cmd.ExecuteScalar();
if (obj != null)
{
res = obj.ToString();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
return res;
}
}
}
都是把那個(gè)SQLITEHelper的操作類搬過來的,改了MySqlConnection等變量名,對(duì)MYSQL來說經(jīng)常會(huì)出現(xiàn)中文亂碼,經(jīng)實(shí)驗(yàn),解決方法:
① 用PHPMYADMIN建立MYSQL數(shù)據(jù)庫(kù)的時(shí)候記得選擇UTF-8的編碼
② 在上面的數(shù)據(jù)庫(kù)操作類中的連接字符串中記得加上charset=utf8
這樣用上面的操作類來插入中文就不會(huì)出現(xiàn)亂碼了。
您可能感興趣的文章:- asp.net Oracle數(shù)據(jù)庫(kù)訪問操作類
- asp.net下使用DbProviderFactories的數(shù)據(jù)庫(kù)操作類
- ASP.NET對(duì)SQLServer的通用數(shù)據(jù)庫(kù)訪問類
- asp.net下Oracle,SQL Server,Access萬(wàn)能數(shù)據(jù)庫(kù)通用類
- asp.net 數(shù)據(jù)庫(kù)連接類代碼(SQL)
- asp.net 數(shù)據(jù)庫(kù)的連接和datatable類
- ASP.NET封裝的SQL數(shù)據(jù)庫(kù)訪問類
- ASP.NET web.config中數(shù)據(jù)庫(kù)連接字符串connectionStrings節(jié)的配置方法
- asp.net連接查詢SQL數(shù)據(jù)庫(kù)并把結(jié)果顯示在網(wǎng)頁(yè)上(2種方法)
- ASP.NET 6種常用數(shù)據(jù)庫(kù)的連接方法
- ASP.NET2.0 SQL Server數(shù)據(jù)庫(kù)連接詳解
- Asp.net把圖片存入數(shù)據(jù)庫(kù)和讀取圖片的方法
- ASP.NET數(shù)據(jù)庫(kù)操作類實(shí)例