1. 程式人生 > >C#連接操作MySQL數據庫 幫助類

C#連接操作MySQL數據庫 幫助類

oca turn con OS com client mman ask AD

最近準備寫一個倉庫管理的項目

  客戶要求使用C#編寫MySQL存儲數據

  為了方便,整理了數據庫操作的工具類

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

/// <summary>
/// @author: 房上的貓
/// 
/// @博客地址: https://www.cnblogs.com/lsy131479/
/// </summary>
namespace ConsoleApp1 { public class MySQLDBHelp { #region 建立MySql數據庫連接 /// <summary> /// 建立數據庫連接. /// </summary> /// <returns>返回MySqlConnection對象</returns> public MySqlConnection getmysqlcon() { string M_str_sqlcon = "
server=localhost;port=3306;user id=root;password=root;database=abc"; //根據自己的設置 MySqlConnection myCon = new MySqlConnection(M_str_sqlcon); return myCon; } #endregion #region 執行MySqlCommand命令 /// <summary> /// 執行MySqlCommand /// </summary>
/// <param name="M_str_sqlstr">SQL語句</param> public void getmysqlcom(string M_str_sqlstr) { MySqlConnection mysqlcon = this.getmysqlcon(); mysqlcon.Open(); MySqlCommand mysqlcom = new MySqlCommand(M_str_sqlstr, mysqlcon); mysqlcom.ExecuteNonQuery(); mysqlcom.Dispose(); mysqlcon.Close(); mysqlcon.Dispose(); } #endregion #region 創建MySqlDataReader對象 /// <summary> /// 創建一個MySqlDataReader對象 /// </summary> /// <param name="M_str_sqlstr">SQL語句</param> /// <returns>返回MySqlDataReader對象</returns> public MySqlDataReader getmysqlread(string M_str_sqlstr) { MySqlConnection mysqlcon = this.getmysqlcon(); MySqlCommand mysqlcom = new MySqlCommand(M_str_sqlstr, mysqlcon); mysqlcon.Open(); MySqlDataReader mysqlread = mysqlcom.ExecuteReader(CommandBehavior.CloseConnection); return mysqlread; } #endregion } }

C#連接操作MySQL數據庫 幫助類