您好,登錄后才能下訂單哦!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.Data;
namespace www.xinduofen.com
{
class MySqlOperateTool
{
private const string serverIP = "localhost";//mysql服務器的IP地址
private const string serverPort = "3306";//mysql服務器的端口
private const string userName = "LGQ";//mysql服務器的用戶名
private const string userPassword = "lgq";//mysql服務器的用戶密碼
/// <summary>
/// MySqlOperateTool工具類的測試方法(供使用MySqlOperateTool工具類的人員進行參考)
/// </summary>
public static void mySqlOperateToolTest() {
MySqlConnection dbConnection = MySqlOperateTool.getConnection("test");
if (dbConnection != null)
{
//創建一個事務
MySqlTransaction transaction = MySqlOperateTool.beginTransaction(dbConnection);
try
{
string sql = "insert into testTable values(1001,'張三','男')";
MySqlOperateTool.executeNonQuery(sql, dbConnection);
sql = "insert into testTable values(1002,'李四','女')";
MySqlOperateTool.executeNonQuery(sql, dbConnection);
////模擬異常
//int aa = 0;
//int bb = 10 / aa;
//提交事務
MySqlOperateTool.transactionCommit(transaction);
}
catch (Exception)
{
//回滾事務
MySqlOperateTool.transactionRollback(transaction);
}
MySqlOperateTool.closeConnection(dbConnection);
}
//MySqlConnection dbConnection = MySqlOperateTool.getConnection("test");
//if (dbConnection != null)
//{
// string sql = "select count(id) from testTable";
// object resultSetCnt = MySqlOperateTool.getSingleObject(sql, dbConnection);
// if (resultSetCnt != null)
// {
// System.Console.WriteLine("resultSetCnt:" + (long)resultSetCnt);
// }
// sql = "select * from testTable";
// MySqlDataReader dataReader = MySqlOperateTool.getDataReader(sql, dbConnection);
// if (dataReader!=null)
// {
// while (dataReader.Read())
// {
// int id = (int)dataReader["id"];
// string name = (string)dataReader["name"];
// string sex = (string)dataReader["sex"];
// System.Console.WriteLine("id:"+id+" name:"+name+" sex:"+sex);
// }
// }
// MySqlOperateTool.closeConnection(dbConnection);
//}
//MySqlConnection dbConnection = MySqlOperateTool.getConnection("test");
//if (dbConnection != null)
//{
// DataSet dataset = new DataSet();//定義一個DataSet
// string sql = "select * from testTable";
// bool resultFlag = MySqlOperateTool.dataAdappterDataSet(sql,dataset,"persons", dbConnection);
// if (resultFlag)
// {
// foreach (DataRow therow in dataset.Tables["persons"].Rows)
// {
// int id = (int)therow["id"];
// string name = (string)therow["name"];
// string sex = (string)therow["sex"];
// System.Console.WriteLine("id:" + id + " name:" + name + " sex:" + sex);
// }
// }
// MySqlOperateTool.closeConnection(dbConnection);
//}
//MySqlConnection dbConnection = MySqlOperateTool.getConnection("test");
//if (dbConnection != null)
//{
// DataSet dataset = new DataSet();//定義一個DataSet
// string sql = "select * from testTable";
// //獲得一個空的用于更新的類對象
// MySqlCommandBuilder commandBuilder = MySqlOperateTool.dataAdappterDataSetUpdate(sql, dataset, "persons", dbConnection);
// if (commandBuilder!=null)
// {
// //更新數據庫的內容(假設數據庫中有兩行以上的人員信息)
// dataset.Tables["persons"].Rows[0]["name"] = "天機小紅";
// dataset.Tables["persons"].Rows[0]["sex"] = "女";
// dataset.Tables["persons"].Rows[1]["name"] = "小李分刀";
// dataset.Tables["persons"].Rows[1]["sex"] = "男";
// commandBuilder.DataAdapter.Update(dataset, "persons");
// }
// MySqlOperateTool.closeConnection(dbConnection);
//}
//MySqlConnection dbConnection = MySqlOperateTool.getConnection("test");
//if (dbConnection != null)
//{
// DataSet dataset = new DataSet();//定義一個DataSet
// string sql = "select * from testTable";
// //獲得一個空的用于更新的類對象
// MySqlCommandBuilder commandBuilder = MySqlOperateTool.dataAdappterDataSetUpdate(sql, dataset, "persons", dbConnection);
// if (commandBuilder != null)
// {
// //向數據庫中添加內容
// DataRow datarow = dataset.Tables["persons"].NewRow();//以此表的字段定義一個新的一行數據
// datarow["id"] = 1003;
// datarow["name"] = "張三";
// datarow["sex"] = "男";
// dataset.Tables["persons"].Rows.Add(datarow);
// datarow = dataset.Tables["persons"].NewRow();//以此表的字段定義一個新的一行數據
// datarow["id"] = 1004;
// datarow["name"] = "李四";
// datarow["sex"] = "女";
// dataset.Tables["persons"].Rows.Add(datarow);
// commandBuilder.DataAdapter.Update(dataset, "persons");
// }
// MySqlOperateTool.closeConnection(dbConnection);
//}
//MySqlConnection dbConnection = MySqlOperateTool.getConnection("test");
//if (dbConnection != null)
//{
// DataSet dataset = new DataSet();//定義一個DataSet
// string sql = "select * from testTable";
// //獲得一個空的用于更新的類對象
// MySqlCommandBuilder commandBuilder = MySqlOperateTool.dataAdappterDataSetUpdate(sql, dataset, "persons", dbConnection);
// if (commandBuilder != null)
// {
// //從數據庫中刪除內容
// DataRow datarow = dataset.Tables["persons"].Rows[2];
// datarow.Delete();
// datarow = dataset.Tables["persons"].Rows[3];
// datarow.Delete();
// commandBuilder.DataAdapter.Update(dataset, "persons");
// }
// MySqlOperateTool.closeConnection(dbConnection);
//}
}
/// <summary>
/// 獲取數據庫連接對象
/// </summary>
/// <param name="dbFile">傳入的數據庫名</param>
/// <returns>返回值為null代表獲取連接失敗</returns>
public static MySqlConnection getConnection(string dbName)
{
MySqlConnection dbConnection = null;
if (string.IsNullOrEmpty(dbName))//如果傳入的參數異常
{
return null;
}
string connectStr = "Data Source=" + serverIP + ";Port=" + serverPort + ";User ID=" + userName + ";Password=" + userPassword + ";Database=" + dbName + ";CharSet=utf8;";
try {
MySqlConnection connection = new MySqlConnection(connectStr);
connection.Open();
//獲得mysql數據庫連接對象成功
dbConnection = connection;
}catch(Exception){
System.Console.WriteLine("C#獲得mysql數據庫連接對象時產生了異常!");
}
return dbConnection;
}
/// <summary>
/// 創建一個事務,并且開始執行事務
/// </summary>
/// <param name="dbConnection">數據庫連接對象</param>
/// <returns>返回為null代表創建事務失敗</returns>
public static MySqlTransaction beginTransaction(MySqlConnection dbConnection)
{
MySqlTransaction transaction = null;
if (dbConnection == null)
{
return null;
}
try
{
transaction = dbConnection.BeginTransaction();//創建事務,并且開始執行事務
}
catch (Exception) {
Console.WriteLine("創建事務時產生了異常!");
}
return transaction;
}
/// <summary>
/// 提交事務
/// </summary>
/// <param name="transaction">與一個事務相關的對象</param>
public static void transactionCommit(MySqlTransaction transaction)
{
try
{
//提交事務
transaction.Commit();
}
catch (Exception)
{
Console.WriteLine("提交事務時產生了異常!");
}
}
/// <summary>
/// 回滾事務
/// </summary>
/// <param name="transaction">與一個事務相關的對象</param>
public static void transactionRollback(MySqlTransaction transaction)
{
try
{
//回滾事務
transaction.Rollback();
}
catch (Exception)
{
Console.WriteLine("回滾事務時產生了異常!");
}
}
/// <summary>
/// 關閉數據庫的連接
/// </summary>
/// <param name="db_connection">數據庫連接對象</param>
public static void closeConnection(MySqlConnection dbConnection)
{
//如果連接不為空
if (dbConnection != null)
{
try {
dbConnection.Close();
}catch(Exception){
System.Console.WriteLine("C#關閉mysql數據庫連接對象時產生了異常!");
}
}
}
/// <summary>
/// 查詢單個信息
/// </summary>
/// <param name="sql">sql查詢語句</param>
/// <param name="db_connection">數據庫連接對象</param>
/// <returns>
/// 如果返回值為null代表查詢失敗;
/// 此方法只能返回一個值,主要用于查行數,等其他用途(傳入的參數均不能為空);
/// 返回 Object 類型的數據,執行查詢,并返回查詢所返回的結果集中第一行的第一列。忽略其他列或行;
/// </returns>
public static Object getSingleObject(string sql, MySqlConnection dbConnection)
{
Object result = null;
if (string.IsNullOrEmpty(sql) || dbConnection == null)//如果傳入參數不合法
{
return null;
}
try
{
MySqlCommand command = new MySqlCommand(sql, dbConnection);//創建數據庫執行命令語句對象
result = command.ExecuteScalar();//此命令只會返回一個值
}
catch (Exception)//如果sql命令執行失敗
{
Console.WriteLine("sql查詢語句不合法或者數據庫連接對象異常!");
}
return result;//返回讀到的值
}
/// <summary>
/// 執行sql語句
/// </summary>
/// <param name="sql">sql執行語句</param>
/// <param name="db_connection">數據庫連接對象</param>
/// <returns>
/// 返回值為0代表sql命令執行后對數據庫無任何影響,如果返回值大于0代表sql命令執行后對數據庫產生了影響;
/// 此方法只能返回一個值(指令在數據庫影響的行數),主要用于執行 insert、delete、alter操作;
/// </returns>
public static int executeNonQuery(string sql, MySqlConnection dbConnection)
{
//sql語句執行后影響的行數,初始化為0
int resultCnt = 0;
if (string.IsNullOrEmpty(sql) || dbConnection == null)//如果傳入參數不合法
{
return 0;
}
try
{
MySqlCommand command = dbConnection.CreateCommand();//創建數據庫執行命令語句對象
command.CommandText = sql;//執行相關的sql語句
resultCnt = command.ExecuteNonQuery();//此命令無查詢功能
}
catch (Exception)//如果sql命令執行失敗
{
Console.WriteLine("sql查詢語句不合法或者數據庫連接對象異常!");
}
return resultCnt;//返回影響的行數
}
/// <summary>
/// 查詢多行信息
/// </summary>
/// <param name="sql">sql查詢語句</param>
/// <param name="db_connection">數據庫連接對象</param>
/// <returns>
/// 返回為null,代表查詢失敗,返回 MySqlDataReader 類型的數據,主要用于檢索多行值;
/// 此方法只能返回 MySqlDataReader 類型的數據,只能一行一行的讀數據;
/// </returns>
public static MySqlDataReader getDataReader(string sql, MySqlConnection dbConnection)
{
MySqlDataReader data_read = null;
if (string.IsNullOrEmpty(sql) || dbConnection == null)//如果傳入參數不合法
{
return null;
}
try
{
MySqlCommand command = dbConnection.CreateCommand();//創建數據庫執行命令語句對象
command.CommandText = sql;//執行相關的sql語句
data_read = command.ExecuteReader();//讀取數據庫中的數據
}
catch (Exception)//如果sql命令執行失敗
{
Console.WriteLine("sql查詢語句不合法或者數據庫連接對象異常!");
}
return data_read;//返回讀到的數據
}
/// <summary>
/// 此方法是向傳入的 dataset 中填入數據,“不支持更新功能”
/// </summary>
/// <param name="sql">sql查詢語句</param>
/// <param name="dataset">用于存儲查詢信息的數據集緩存區</param>
/// <param name="table_name">是dataset要緩存查詢信息的DataTble名稱</param>
/// <param name="db_connection">數據庫連接對象</param>
/// <returns>查詢成功返回true,失敗返回false</returns>
public static bool dataAdappterDataSet(string sql, DataSet dataset, string table_name, MySqlConnection dbConnection)
{
//初始化查詢失敗
bool result = false;
if (string.IsNullOrEmpty(sql) || dataset == null || string.IsNullOrEmpty(table_name) || dbConnection==null)
{
return false;
}
try
{
//定義將數據庫的數據匹配到DataSet的適配器對象
MySqlDataAdapter data_adappter = new MySqlDataAdapter(sql, dbConnection);
data_adappter.Fill(dataset, table_name);
result = true;//查詢成功
}
catch (Exception)//如果sql命令執行失敗
{
Console.WriteLine("sql查詢語句不合法或者數據庫連接對象異常!");
}
return result;//返回查詢結果
}
/// <summary>
/// 此方法是向傳入的 dataset 中填入數據,“支持更新功能”,執行更新之前不能斷開與數據庫的連接
/// </summary>
/// <param name="sql">sql查詢語句</param>
/// <param name="dataset">用于存儲查詢信息的數據集緩存區</param>
/// <param name="table_name">是dataset要緩存查詢信息的DataTble名稱</param>
/// <param name="db_connection">數據庫連接對象</param>
/// <returns>返回一個 MySqlCommandBuilder 對象,可以用來進行更新操作,將內存dataset中改變的數據同步到數據庫中</returns>
public static MySqlCommandBuilder dataAdappterDataSetUpdate(string sql, DataSet dataset, string table_name, MySqlConnection dbConnection)
{
MySqlCommandBuilder commandBuilder = null;
if (string.IsNullOrEmpty(sql) || dataset == null || string.IsNullOrEmpty(table_name) || dbConnection == null)
{
return null;
}
try
{
//定義將數據庫的數據匹配到DataSet的適配器對象
MySqlDataAdapter data_adappter = new MySqlDataAdapter(sql, dbConnection);
MySqlCommandBuilder builder = new MySqlCommandBuilder(data_adappter);
data_adappter.Fill(dataset, table_name);
commandBuilder = builder;//查詢成功
}
catch (Exception)//如果sql命令執行失敗
{
Console.WriteLine("sql查詢語句不合法或者數據庫連接對象異常!");
}
return commandBuilder;//查詢結束,返回commandBuilder
}
}
}
內容來自:越康體育
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。