c#教程https://www.jxasp.com/blog
这几天学习数据库操作,就自己封装了一个数据库操作类,下面是代码展示
下面的例子是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()方法的参数要注意,因中间还有一个参数有默认值,
所以要用指定参数名值的格式(形参名:实参名),不然是通不过的.