C# 資料庫操作封裝
阿新 • • 發佈:2019-02-17
絕大多數程式,想要實現資料互動,資料儲存,都離不開資料庫,無論是桌面客戶端應用程式,網站,還是手機APP。這裡講解了C#中MySQL資料庫操作封裝,如其它資料庫(SQLServer也差不多),封裝了sql語句的查詢、修改、插入、刪除操作,以及儲存過程的執行,包括有輸入、輸出引數的儲存過程,儲存過程的執行無需輸入任何引數名稱,只需輸入引數值即可。
1.資料庫封裝介面
using System;
using System.Data;
namespace DBClass
{
public interface IDBfun : IDisposable
{
string ConnectionString { get; set; }
void SetDBConnectionPararmeter(string server,
string database,
string username,
string password,
int port = 3306);
int ExecSQL(string sqlString, object[] prams);
int ExecSQL(string sqlString);
DataSet ExecSQLQuery(string sqlString, //命令文字
object[] prams); //引數物件
DataSet ExecSQLQuery(string sqlString, //命令文字
object[] prams, //引數物件
string tbName); //資料表名稱
DataSet ExecSQLQuery(string sqlString, //命令文字
object[] prams, //引數物件
string tbName, //資料表名稱
ref object objcmd //返回SqlCommand
);
DataSet ExecSQLQuery(object objcmd); //執行SqlCommand
DataSet ExecSQLQuery(string sqlString);
object MakeInParam(string paramName, //儲存過程名稱或命令文字
SqlDbType dbType, //引數型別
int size, //引數大小
object value); //引數值
int SavePictureToDB(byte[] imageByte,
string picturename,
string picType,
int picTypeId);
int UpdatePictureToDb(byte[] imageByte, string pictureName, string picType, int picTypeId);
int GetPictureFromDB(ref byte[] byPictureBytes,
string picType,
int picTypeId);
}
}
2.繼承介面實現
using System;
using System.Data;
using MySql.Data.MySqlClient;
namespace DBClass
{
public class DBMySQL : IDBfun
{
public string ConnectionString { get; set; }
public DBMySQL()
{
ConnectionString = "";
}
public DBMySQL(string server,
string database,
string username,
string password,
int port = 3306)
{
ConnectionString = "Data Source=" + server + //建立資料庫連線串
";DataBase=" + database +
";User ID=" + username +
";Password=" + password +
";Port=" + port +
";Charset=utf8" +
";default command timeout=0" + //此字元表示將命令超時時間改為無限等待
";Allow Zero DateTime=True"; //此字串用於將資料庫的DateTime型別裝換
}
public void Dispose()
{
}
public void SetDBConnectionPararmeter(string server,
string database,
string username,
string password,
int port = 3306)
{
ConnectionString = "Data Source=" + server + //建立資料庫連線串
";DataBase=" + database +
";User ID=" + username +
";Password=" + password +
";Port=" + port +
";Charset=utf8";
}
/// <summary>
/// 儲存圖片到資料庫
/// </summary>
/// <param name="imageByte"></param>
/// <param name="picturename"></param>
/// <param name="picType"></param>
/// <param name="picTypeId"></param>
/// <returns></returns>
public int SavePictureToDB(byte[] imageByte,
string picturename,
string picType,
int picTypeId)
{
var result = 0;
try
{
if (imageByte != null && imageByte.Length != 0)
{
using (var conn = new MySqlConnection())
{
conn.ConnectionString = ConnectionString;
conn.Open();
var insertStr = @"INSERT INTO studentmanager.picture
(
Picturename,
PicType,
PicTypeId,
imageByte
)
VALUES
(
@Picturename,
@PicType,
@PicTypeId,
@imageByte
);";
var comm = new MySqlCommand();
comm.Connection = conn;
comm.CommandText = insertStr;
comm.CommandType = CommandType.Text;
//設定資料庫欄位型別MediumBlob的值為圖片位元組陣列imageByte
comm.Parameters.Add(new MySqlParameter("@imageByte", MySqlDbType.MediumBlob)).Value = imageByte;
comm.Parameters.Add(new MySqlParameter("@Picturename", MySqlDbType.VarChar)).Value = picturename;
comm.Parameters.Add(new MySqlParameter("@PicType", MySqlDbType.VarChar)).Value = picType;
comm.Parameters.Add(new MySqlParameter("@PicTypeId", MySqlDbType.Int32)).Value = picTypeId;
//execute sql
result = comm.ExecuteNonQuery();
comm.Dispose();
conn.Close();
conn.Dispose();
}
}
}
catch (Exception)
{
// throw ex;
}
return result;
}
/// <summary>
/// 更新圖片
/// </summary>
/// <param name="imageByte"></param>
/// <param name="pictureName"></param>
/// <param name="picType"></param>
/// <param name="picTypeId"></param>
/// <returns></returns>
public int UpdatePictureToDb(byte[] imageByte, string pictureName, string picType, int picTypeId)
{
var result = 0;
try
{
if (imageByte != null && imageByte.Length != 0)
{
using (var conn = new MySqlConnection())
{
conn.ConnectionString = ConnectionString;
conn.Open();
var insertStr = @"UPDATE studentmanager.picture
SET
Picturename = @Picturename ,
imageByte = @imageByte
WHERE
PicType = @PicType AND PicTypeId = @PicTypeId ";
var comm = new MySqlCommand
{
Connection = conn,
CommandText = insertStr,
CommandType = CommandType.Text
};
//設定資料庫欄位型別MediumBlob的值為圖片位元組陣列imageByte
comm.Parameters.Add(new MySqlParameter("@imageByte", MySqlDbType.MediumBlob)).Value = imageByte;
comm.Parameters.Add(new MySqlParameter("@Picturename", MySqlDbType.VarChar)).Value = pictureName;
comm.Parameters.Add(new MySqlParameter("@PicType", MySqlDbType.VarChar)).Value = picType;
comm.Parameters.Add(new MySqlParameter("@PicTypeId", MySqlDbType.Int32)).Value = picTypeId;
//execute sql
result = comm.ExecuteNonQuery();
comm.Dispose();
conn.Close();
conn.Dispose();
}
}
}
catch (Exception)
{
// throw ex;
}
return result;
}
public int GetPictureFromDB(ref byte[] byPictureBytes,
string picType,
int picTypeId)
{
try
{
using (var conn = new MySqlConnection())
{
conn.ConnectionString = ConnectionString;
conn.Open();
//設定命令引數
var sqLstring = $@"SELECT
imageByte
FROM
studentmanager.picture
WHERE PicType ='{picType}' AND PicTypeId='{picTypeId}'";
var comm = new MySqlCommand(sqLstring, conn);
//執行命令並獲得資料讀取器
var dr = comm.ExecuteReader();
if (dr.Read())
{
try
{
//讀出圖片位元組陣列至byte[]
var len = dr.GetBytes(0, 0, null, 0, int.MaxValue);
byPictureBytes = new byte[len];
if (byPictureBytes.Length != 0)
dr.GetBytes(0, 0, byPictureBytes, 0, byPictureBytes.Length);
}
catch (Exception)
{
// ignored
}
}
dr.Dispose();
comm.Dispose();
conn.Close();
conn.Dispose();
}
}
catch (Exception)
{
// throw ex;
}
return 0;
}
public DataSet ExecSQLQuery(string sqlString, object[] prams)
{
MySqlDataAdapter dap;
DataSet dsRet = null;
if (string.IsNullOrEmpty(ConnectionString))
{
throw new Exception("ConnectionString Error");
}
if (string.IsNullOrEmpty(sqlString))
{
throw new Exception("SQL String Error");
}
if (!DsafConnectionTest())
{
throw new Exception("Database Connect Error");
}
try
{
using (var conn = new MySqlConnection())
{
conn.ConnectionString = ConnectionString;
conn.Open();
dap = CreateDataAdaper(sqlString, prams, conn); //建立橋接器物件
dsRet = new DataSet(); //建立資料集物件
dap.Fill(dsRet); //填充資料集
conn.Close();
conn.Dispose();
}
}
catch (MySqlException)
{
// // throw ex;
}
catch (Exception)
{
// // throw ex;
}
return dsRet; //返回資料集
}
/// <summary>
/// 初始化引數值
/// </summary>
private object MakeParam(string paramName, //儲存過程名稱或命令文字
MySqlDbType dbType, //引數型別
int size, //引數大小
ParameterDirection direction, //引數方向
object value) //引數值
{
MySqlParameter param; //宣告SQL引數物件
if (size > 0) //判斷引數欄位是否大於0
param = new MySqlParameter(paramName, dbType, size); //根據指定的型別和大小建立SQL引數
else
param = new MySqlParameter(paramName, dbType); //根據指定的型別建立SQL引數
param.Direction = direction; //設定SQL引數的型別
if (!(direction == ParameterDirection.Output && value == null)) //判斷是否為輸出引數
param.Value = value; //設定引數返回值
//轉換object物件返回
return param; //返回SQL引數
}
#region 將命令文字新增到SqlDataAdapter
/// <summary>
/// 建立一個SqlDataAdapter物件以此來執行命令文字
/// </summary>
private MySqlDataAdapter CreateDataAdaper(string sqLstring, //命令文字
object[] prams,
MySqlConnection conn) //引數物件
{
var dap = new MySqlDataAdapter(sqLstring, conn); //建立橋接器物件
dap.SelectCommand.CommandType = CommandType.Text; //指定要執行的型別為命令文字
if (prams != null) //判斷SQL引數是否不為空
{
foreach (var parameter in prams) //遍歷傳遞的每個SQL引數
{
var param = (MySqlParameter)parameter;
dap.SelectCommand.Parameters.Add(param); //將SQL引數新增到執行命令物件中
}
}
//加入返回引數
dap.SelectCommand.Parameters.Add(new MySqlParameter("ReturnValue",
MySqlDbType.Int32,
4,
ParameterDirection.ReturnValue,
false,
0,
0,
string.Empty,
DataRowVersion.Default,
null));
//返回橋接器物件
return dap;
}
#endregion
#region 將命令文字新增到SqlCommand
/// <summary>
/// 建立一個SqlCommand物件以此來執行命令文字
/// </summary>
private MySqlCommand CreateCommand(string procName, //命令文字
object[] prams,
MySqlConnection conn) //命令文字所需引數
{
var cmd = new MySqlCommand(procName, conn); //建立SqlCommand命令物件
cmd.CommandType = CommandType.Text; //指定要執行的型別為命令文字
// 依次把引數傳入命令文字
if (prams != null) //判斷SQL引數是否不為空
{
foreach (var parameter in prams) //遍歷傳遞的每個SQL引數
{
var param = (MySqlParameter)parameter;
cmd.Parameters.Add(param); //將SQL引數新增到執行命令物件中
}
}
//加入返回引數
cmd.Parameters.Add(new MySqlParameter("ReturnValue",
MySqlDbType.Int32,
4,
ParameterDirection.ReturnValue,
false,
0,
0,
string.Empty,
DataRowVersion.Default,
null));
//返回SqlCommand命令物件
return cmd;
}
#endregion
#region 執行引數命令文字(無資料庫中資料返回)
/// <summary>
/// 執行命令
/// </summary>
public int ExecSQL(string sqlString, //命令文字
object[] prams) //引數物件
{
var nRet = 0;
MySqlCommand cmd;
MySqlTransaction transaction = null;
if (string.IsNullOrEmpty(ConnectionString))
{
throw new Exception("ConnectionString Error");
}
if (string.IsNullOrEmpty(sqlString))
{
throw new Exception("SQL String Error");
}
if (!DsafConnectionTest())
{
throw new Exception("Database Connect Error");
}
try
{
using (var conn = new MySqlConnection())
{
conn.ConnectionString = ConnectionString;
conn.Open();
transaction = conn.BeginTransaction();
cmd = CreateCommand(sqlString, prams, conn); //建立SqlCommand命令物件
cmd.Transaction = transaction;
nRet = cmd.ExecuteNonQuery(); //執行SQL命令
transaction.Commit();
conn.Close();
conn.Dispose();
}
}
catch (MySqlException)
{
transaction?.Rollback();
}
catch (Exception)
{
// ignored
}
return nRet;
}
/// <summary>
/// 直接執行SQL語句
/// </summary>
public int ExecSQL(string sqlString)
{
var nRet = 0;
MySqlCommand cmd;
MySqlTransaction transaction = null;
if (string.IsNullOrEmpty(ConnectionString))
{
throw new Exception("ConnectionString Error");
}
if (string.IsNullOrEmpty(sqlString))
{
throw new Exception("SQL String Error");
}
if (!DsafConnectionTest())
{
throw new Exception("Database Connect Error");
}
try
{
using (var conn = new MySqlConnection())
{
conn.ConnectionString = ConnectionString;
conn.Open();
transaction = conn.BeginTransaction();
cmd = new MySqlCommand(sqlString, conn); //建立SqlCommand命令物件
cmd.Transaction = transaction;
nRet = cmd.ExecuteNonQuery(); //執行SQL命令
transaction.Commit();
conn.Close();
conn.Dispose();
}
}
catch (MySqlException)
{
transaction?.Rollback();
}
catch (Exception)
{
// ignored
}
//返回>0,表示執行成功
return nRet;
}
#region 執行引數命令文字(有返回值)
/// <summary>
/// 執行查詢命令文字,並且返回DataSet資料集
/// </summary>
public DataSet ExecSQLQuery(string sqlString, //命令文字
object[] prams, //引數物件
string tbName) //資料表名稱
{
MySqlDataAdapter dap;
DataSet dsRet = null;
if (string.IsNullOrEmpty(ConnectionString))
{
throw new Exception("ConnectionString Error");
}
if (string.IsNullOrEmpty(sqlString))
{
throw new Exception("SQL String Error");
}
if (!DsafConnectionTest())
{
throw new Exception("Database Connect Error");
}
try
{
using (var conn = new MySqlConnection())
{
conn.ConnectionString = ConnectionString;
conn.Open();
dap = CreateDataAdaper(sqlString, prams, conn); //建立橋接器物件
dsRet = new DataSet(); //建立資料集物件
dap.Fill(dsRet, tbName); //填充資料集
conn.Close();
conn.Dispose();
}
}
catch (MySqlException)
{
// // throw ex;
}
catch (Exception)
{
// // throw ex;
}
return dsRet; //返回資料集
}
public DataSet ExecSQLQuery(string sqlString, //命令文字
object[] prams, //引數物件
string tbName, //資料表名稱
ref object cmd //返回SQL command
)
{
MySqlDataAdapter dap;
DataSet dsRet = null;
if (string.IsNullOrEmpty(ConnectionString))
{
throw new Exception("ConnectionString Error");
}
if (string.IsNullOrEmpty(sqlString))
{
throw new Exception("SQL String Error");
}
if (!DsafConnectionTest())
{
throw new Exception("Database Connect Error");
}
try
{
using (var conn = new MySqlConnection())
{
conn.ConnectionString = ConnectionString;
conn.Open();
dap = CreateDataAdaper(sqlString, prams, conn); //建立橋接器物件
dsRet = new DataSet(); //建立資料集物件
dap.Fill(dsRet, tbName); //填充資料集
cmd = dap.SelectCommand;
conn.Close();
conn.Dispose();
}
}
catch (MySqlException)
{
// throw ex;
}
catch (Exception)
{
// throw ex;
}
return dsRet; //返回資料集
}
//執行一個SQL命令體
public DataSet ExecSQLQuery(object cmd) //命令物件
{
MySqlDataAdapter dap;
DataSet dsRet = null;
if (string.IsNullOrEmpty(ConnectionString))
{
throw new Exception("ConnectionString Error");
}
if (!DsafConnectionTest())
{
throw new Exception("Database Connect Error");
}
try
{
using (var conn = new MySqlConnection())
{
conn.ConnectionString = ConnectionString;
conn.Open();
dap = new MySqlDataAdapter((MySqlCommand)cmd); //建立橋接器物件
dsRet = new DataSet(); //建立資料集物件
dap.Fill(dsRet); //填充資料集
conn.Close();
conn.Dispose();
}
}
catch (MySqlException)
{
// throw ex;
}
catch (Exception)
{
// throw ex;
}
return dsRet; //返回資料集
}
public DataSet ExecSQLQuery(string sqlString)
{
MySqlDataAdapter dap;
DataSet dsRet = null;
if (string.IsNullOrEmpty(ConnectionString))
{
throw new Exception("ConnectionString Error");
}
if (string.IsNullOrEmpty(sqlString))
{
throw new Exception("SQL String Error");
}
if (!DsafConnectionTest())
{
throw new Exception("Database Connect Error");
}
try
{
using (var conn = new MySqlConnection())
{
conn.ConnectionString = ConnectionString;
conn.Open();
dap = CreateDataAdaper(sqlString, null, conn); //建立橋接器物件
dsRet = new DataSet(); //建立資料集物件
dap.Fill(dsRet); //填充資料集
conn.Close();
conn.Dispose();
}
}
catch (MySqlException)
{
// throw ex;
}
catch (Exception)
{
// throw ex;
}
return dsRet; //返回資料集
}
#endregion
private bool DsafConnectionTest()
{
var bRet = false;
try
{
using (var conn = new MySqlConnection())
{
conn.ConnectionString = ConnectionString;
conn.Open();
bRet = true;
conn.Close();
conn.Dispose();
}
}
catch (MySqlException)
{
//// throw ex;
// CommonFunction.MessageShow("資料庫連線失敗", "提示", "OK", "Information");
}
return bRet;
}
#endregion
#region 傳入引數並且轉換為SqlParameter型別
/// <summary>
/// 轉換引數
/// </summary>
public object MakeInParam(string paramName, //儲存過程名稱或命令文字
SqlDbType dbType, //引數型別
int size, //引數大小
object value) //引數值
{
var mydbtype = TransTypeFromSqlDBtype(dbType);
return MakeParam(paramName, mydbtype, size, ParameterDirection.Input, value); //建立SQL引數
}
private MySqlDbType TransTypeFromSqlDBtype(SqlDbType dbType)
{
MySqlDbType dbRet = 0;
switch (dbType)
{
case SqlDbType.BigInt:
dbRet = MySqlDbType.Int32;
break;
case SqlDbType.Binary:
dbRet = MySqlDbType.Binary;
break;
case SqlDbType.Char:
dbRet = MySqlDbType.Byte;
break;
case SqlDbType.Date:
dbRet = MySqlDbType.Date;
break;
case SqlDbType.DateTime:
dbRet = MySqlDbType.DateTime;
break;
case SqlDbType.DateTime2:
dbRet = MySqlDbType.DateTime;
break;
case SqlDbType.DateTimeOffset:
dbRet = MySqlDbType.Timestamp;
break;
case SqlDbType.Decimal:
dbRet = MySqlDbType.Decimal;
break;
case SqlDbType.Float:
dbRet = MySqlDbType.Float;
break;
case SqlDbType.Image:
dbRet = MySqlDbType.LongBlob;
break;
case SqlDbType.Int:
dbRet = MySqlDbType.Int32;
break;
case SqlDbType.Money:
dbRet = MySqlDbType.Double;
break;
case SqlDbType.NChar:
dbRet = MySqlDbType.UByte;
break;
case SqlDbType.NText:
dbRet = MySqlDbType.Text;
break;
case SqlDbType.NVarChar:
dbRet = MySqlDbType.Text;
break;
case SqlDbType.Real:
dbRet = MySqlDbType.Double;
break;
case SqlDbType.SmallDateTime:
dbRet = MySqlDbType.Newdate;
break;
case SqlDbType.SmallInt:
dbRet = MySqlDbType.Int16;
break;
case SqlDbType.SmallMoney:
dbRet = MySqlDbType.Float;
break;
case SqlDbType.Text:
dbRet = MySqlDbType.Text;
break;
case SqlDbType.Time:
dbRet = MySqlDbType.Time;
break;
case SqlDbType.Timestamp:
dbRet = MySqlDbType.Timestamp;
break;
case SqlDbType.TinyInt:
dbRet = MySqlDbType.Int16;
break;
case SqlDbType.UniqueIdentifier:
dbRet = MySqlDbType.Guid;
break;
case SqlDbType.VarBinary:
dbRet = MySqlDbType.VarBinary;
break;
case SqlDbType.VarChar:
dbRet = MySqlDbType.VarChar;
break;
case SqlDbType.Variant:
dbRet = MySqlDbType.VarString;
break;
case SqlDbType.Xml:
dbRet = MySqlDbType.LongText;
break;
}
return dbRet;
}
#endregion
}
}
3.工程類建立資料庫訪問物件
namespace DBClass
{
public class DbFactory
{
public static IDBfun Create(string dBtype)
{
if (dBtype == "MySQL")
return new DBMySQL();
return new DBSQL();
}
public static IDBfun Create(string dBtype,
string server,
string database,
string username,
string password,
int port = 3306)
{
if (dBtype == "MySQL")
return new DBMySQL(server, database, username, password, port);
return new DBSQL(server, database, username, password);
}
}
}
4.建立例項操作資料庫
using System;
using System.Data;
using Common;
using DBClass;
using MySql.Data.MySqlClient;
namespace StudentManageTool.Plugs
{
public class DBHelper
{
private readonly IDBfun db;
public DBHelper(string DBType,
string DBServer,
string DBDataBase,
string DBUser,
string DBPwd,
int port
)
{
db = DbFactory.Create(DBType, DBServer, DBDataBase, DBUser, DBPwd, port);
}
public object MakeInParam(string ParamName, //儲存過程名稱或命令文字
SqlDbType DbType, //引數型別
int Size, //引數大小
object Value) //引數值
{
var mydbtype = TransTypeFromSqlDBtype(DbType);
return MakeParam(ParamName, mydbtype, Size, ParameterDirection.Input, Value); //建立SQL引數
}
/// <summary>
/// 初始化引數值
/// </summary>
private object MakeParam(string ParamName, //儲存過程名稱或命令文字
MySqlDbType DbType, //引數型別
int Size, //引數大小
ParameterDirection Direction, //引數方向
object Value) //引數值
{
MySqlParameter param; //宣告SQL引數物件
if (Size > 0) //判斷引數欄位是否大於0
param = new MySqlParameter(ParamName, DbType, Size); //根據指定的型別和大小建立SQL引數
else
param = new MySqlParameter(ParamName, DbType); //根據指定的型別建立SQL引數
param.Direction = Direction; //設定SQL引數的型別
if (!(Direction == ParameterDirection.Output && Value == null)) //判斷是否為輸出引數
param.Value = Value; //設定引數返回值
//轉換object物件返回
return param; //返回SQL引數
}
public int ExecSQLInt(string SQLString, object[] prams)
{
return db.ExecSQL(SQLString, prams);
}
public DataSet ExecSQL(string SQLString, object[] prams)
{
return db.ExecSQLQuery(SQLString, prams);
}
public DataSet GetResult(string sqlStr)
{
var ds = new DataSet();
try
{
ds = db.ExecSQLQuery(sqlStr);
if (ds != null && ds.Tables[0].Rows.Count != 0)
{
return ds;
}
}
catch (Exception ex)
{
CommonFunction.MessageShow(ex.Message);
}
return null;
}
public int GetResultInt(string sqlStr)
{
try
{
var ds = db.ExecSQL(sqlStr);
return ds;
}
catch (Exception ex)
{
CommonFunction.MessageShow(ex.Message);
}
return 0;
}
/// <summary>
/// 儲存圖片
/// </summary>
/// <returns></returns>
public int SavePictureToDB(byte[] imageByte, string Picturename, string PicType, int PicTypeId)
{
return db.SavePictureToDB(imageByte, Picturename, PicType, PicTypeId);
}
public int UpdatePictureToDb(byte[] imageByte, string pictureName, string picType, int picTypeId)
{
return db.UpdatePictureToDb(imageByte, pictureName, picType, picTypeId);
}
/// <summary>
/// 獲取圖片
/// </summary>
///