1. 程式人生 > 其它 >C#自己封裝資料庫操作類BaseADO

C#自己封裝資料庫操作類BaseADO

這幾天學習資料庫操作,就自己封裝了一個數據庫操作類,下面是程式碼展示

下面的例子是Access資料庫

也可能用在Sql資料庫中,只在在第一行程式碼上修改識別符號即可

#define OLEDB_

using System;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
namespace MYDATACLASS
{
#if OLEDB_
using MyCommand = OleDbCommand;
using MyConnection = OleDbConnection;
using MyDataAdapter = OleDbDataAdapter;
using MyDataRead = OleDbDataReader;
using MyParameter = OleDbParameter;

#elif SQL_
using MyCommand = SqlCommand;
using MyConnection = SqlConnection;
using MyDataAdapter = SqlDataAdapter;
using MyCommandBuilder = SqlCommandBuilder;
using MyParameter = SqlParameter;
using MyDataRead = SqlDataReader;

//....
#endif


/// <summary>
/// 封裝對數庫操作的靜態方法類
/// <para>GetTable 獲得要查詢的DataTable表</para>
/// <para>GetDataSet 獲得查詢的DataSet表的集合</para>
/// <para>GetDataRead 獲得查詢的DataRead物件</para>
/// <para>ExecuteNonQuery 執行資料的增,刪,改等操作</para>
/// <para>ImageToByte,BetyToImage,位元組byte[]和Image相互轉換</para>
/// <para>版權:greenleaf1976</para>
/// <para>建立時間:2021-07-16</para>
/// </summary>
public class BaseADO
{
public static MyConnection conn = null;

public static string Conn_String= @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\MyAccessFile\newToxinlu.accdb";

public BaseADO() { }

~BaseADO()
{
conn.Dispose();
//CloseConn();
}

/// <summary>
/// 初始化Conn物件,並開啟連線
/// </summary>
private static void InitConnection()
{
if (conn == null)
conn = new MyConnection(Conn_String);
if (conn.State == ConnectionState.Closed)
conn.Open();
if(conn.State==ConnectionState.Broken)
{
conn.Close();
conn.Open();
}
}

/// <summary>
/// 獲得查詢結果的表,如果只想用Sql語句,後面引數可省略
/// <para>如果用Sql+引數列表查詢,格式為:</para>
/// <para>(sql,mPars:pars)格式跳過中間的引數,也就是給指定的引數賦值</para>
/// </summary>
/// <param name="sqlStr">Sql語句或是儲存過程名</param>
/// <param name="cmdType">選擇用Sql語句還是儲存過程查詢</param>
/// <param name="mPars">引數列表</param>
/// <returns></returns>
public static DataTable GetDataTable(string sqlStr, CommandType cmdType = CommandType.Text, params MyParameter[] mPars)
{
InitConnection();
DataTable dt = new DataTable();
MyCommand cmd = null;
MyDataAdapter da = null;
try
{
cmd = new MyCommand(sqlStr, conn);
cmd.CommandType = cmdType;
if(mPars.Length!=0)
{
cmd.Parameters.Clear();
cmd.Parameters.AddRange(mPars);
}
da = new MyDataAdapter(cmd);
da.Fill(dt);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
da.Dispose();
cmd.Dispose();
conn.Close();
}

return dt;
}

/// <summary>
/// 獲得Sql語句或是儲存過程查詢的表的集合
/// </summary>
/// <param name="sqlStr">Sql語句或是儲存過程名</param>
/// <param name="cmdType">是用Sql語句還是儲存過程查詢</param>
/// <param name="mPars">引數列表</param>
/// <returns>查詢表的集合DataSet</returns>
public static DataSet GetDataSet(string sqlStr, CommandType cmdType = CommandType.Text, params MyParameter[] mPars)
{
InitConnection();
DataSet ds = new DataSet();
MyDataAdapter da = null;
MyCommand cmd = null;
try
{
cmd = new MyCommand();
cmd.CommandText = sqlStr;
cmd.Connection = conn;
cmd.CommandType = cmdType;
if(mPars.Length!=0)
{
cmd.Parameters.Clear();
cmd.Parameters.AddRange(mPars);
}
da = new MyDataAdapter(cmd);
da.Fill(ds);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cmd.Dispose();
da.Dispose();
conn.Close();
}
return ds;
}
/// <summary>
/// 通過Sql語句查詢,返回DataRead物件
/// <para>不能斷開連線,查詢後手動關閉連線</para>
/// <para>多用於遞迴載入資料用</para>
/// </summary>
/// <param name="sqlStr"></param>
/// <returns></returns>
public static MyDataRead GetDataRead(string sqlStr,CommandType cmdType=CommandType.Text,params MyParameter[] pras)
{
InitConnection();
MyDataRead dr = null;
MyCommand cmd = null;
try
{
cmd = new MyCommand(sqlStr, conn);
cmd.CommandType = cmdType;
dr = cmd.ExecuteReader();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
return dr;
}

/// <summary>
/// 用Sql語句,引數列表對資料庫的
/// Insert,Update,Delete執行操作
/// </summary>
/// <param name="sql"></param>
/// <param name="mPars"></param>
/// <returns></returns>
public static int ExecuteNonQuery(string sql,CommandType cmdType=CommandType.Text, params MyParameter[] mPars)
{
InitConnection();
int nRet = 0;
MyCommand cmd = null;
try
{
cmd = new MyCommand(sql, conn);
cmd.CommandType = cmdType;
if(mPars.Length!=0)
{
cmd.Parameters.Clear();
cmd.Parameters.AddRange(mPars);
}
nRet =cmd.ExecuteNonQuery();
}
catch (System.Exception ex)
{

MessageBox.Show(ex.Message);
}
finally
{
cmd.Dispose();
conn.Close();
}
return nRet;
}

/// <summary>
/// 圖片(Image)格式轉為位元組(byte[])格式
/// </summary>
/// <param name="_image"></param>
/// <returns></returns>
public static byte[] ImageToByte(Image _image)
{
MemoryStream ms = new MemoryStream();
_image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}

/// <summary>
/// 位元組(byte[])轉為圖片(Image)格式
/// </summary>
/// <param name="buff"></param>
/// <returns></returns>
public static Image BetyToImage(byte[] buff)
{
MemoryStream memoryStream = new MemoryStream(buff, 0, buff.Length);
memoryStream.Write(buff, 0, buff.Length);
Image image = null;
try
{
//位元組陣列轉成Image物件
image = Image.FromStream(memoryStream);
}
catch (Exception)
{
throw;
}
return image;
}
}
基本上有這幾個方法就能操作資料庫了.

特別要說的是GetDataRead()這個方法是要連線資料庫操作的,一般我用在資料遞迴中

最後遞迴完了手動關閉連線,其他的方法都是斷開連線操作的,函式返回前就關閉了連線,

所以在外面呼叫的時候就不用關閉資料庫連線了.

在寫個類繼承BaseADO類,在子類寫實際的資料庫操作方法

下面以修改資料庫資料為例;

/// <summary>
/// 更新指定id的資料庫資料
/// </summary>
/// <param name="stu">要更新的資料結構</param>
/// <param name="id">要更新的查詢id</param>
/// <returns></returns>
public static int UpdateAllData(STUDENT_INFO stu,string id)
{
string sql = "update {0} set mName=@name,mSex=@sex,mAge=@age,mTel=@tel,";
sql += "mFenZu =@fenzu,mBirthday=@birthday,mQQ=@qq,mAddess=@addess,";
sql += "mBeiZu =@beizu,mPicBytes=@picbytes where mID=@mid";
sql = string.Format(sql, MYTABLE_NAME);
//STUDENT_INFO stu = GetDataToStudentInfo();

MyParameter[] pars =
{
new MyParameter("@name",stu.name),
new MyParameter("@sex",stu.sex),
new MyParameter("@age",stu.age),
new MyParameter("@tel",stu.tel),
new MyParameter("@fenzu",stu.fenzu),
new MyParameter("@birthday",stu.birthday),
new MyParameter("@qq",stu.qq),
new MyParameter("@addess",stu.addess),
new MyParameter("@beizu",stu.beizu),
new MyParameter("@picbytes",stu.picBytes),
new MyParameter("@mid",id)
};

return ExecuteNonQuery(sql, mPars:pars);
}
是後呼叫的這個ExecuteNonQuery()方法的引數要注意,因中間還有一個引數有預設值,

所以要用指定引數名值的格式(形參名:實參名),不然是通不過的.

簽名:GreenLeaf1976