C# OleDBHelper(数据库访问公共接口)

    xiaoxiao2025-04-03  15

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.OleDb; namespace OleDbHelper_TEST { public class OleDbHelper { public OleDbHelper() { } private static OleDbConnection Conn; private static OleDbCommand Cmd; private static OleDbDataAdapter Da; private static DataSet Ds; private static DataTable Dt; private static string strConn = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=c:\\a.mdb"; public static void setConn(string FileName) { strConn = "Provider=Microsoft.Jet.OleDb.4.0;Data Source="+FileName; } /// <summary> /// 打开连接 /// </summary> public static void Open() { Conn = new OleDbConnection(); Cmd = new OleDbCommand(); if (Conn.State.Equals(ConnectionState.Closed)) { Conn.ConnectionString = strConn; Conn.Open(); } Cmd.Connection = Conn; } /// <summary> /// 关闭连接 /// </summary> public static void Close() { if (Conn.State.Equals(ConnectionState.Open)) { Conn.Close(); Conn.Dispose(); } } /// <summary> /// 执行ExecuteNonQuery() /// </summary> /// <param name="sql">SQL语句</param> /// <returns></returns> public static int ExecuteCmd(string sql) { try { Open(); Cmd.CommandText = sql; return Cmd.ExecuteNonQuery(); } catch (Exception e) { throw new Exception(e.Message, e); } finally { Close(); } } /// <summary> /// DataSet类 /// </summary> /// <param name="sql">SQL语句</param> /// <returns></returns> public static DataSet GetDataSet(string sql) { try { Open(); Cmd.CommandText = sql; Da = new OleDbDataAdapter(); Da.SelectCommand = Cmd; Ds = new DataSet(); Da.Fill(Ds); return Ds; } catch (Exception e) { throw new Exception(e.Message, e); } finally { Close(); } } /// <summary> /// DataTable 类 /// </summary> /// <param name="sql">SQL语句</param> /// <returns></returns> public static DataTable GetDataTable(string sql) { try { Open(); Cmd.CommandText = sql; Da = new OleDbDataAdapter(); Da.SelectCommand = Cmd; Dt = new DataTable(); Da.Fill(Dt); return Dt; } catch (Exception e) { throw new Exception(e.Message, e); } finally { Close(); } } /// <summary> /// 执行 ExecuteScalar /// </summary> /// <param name="sql">SQL语句</param> /// <returns></returns> public static object ExecuteScalar(string sql) { try { Open(); Cmd.CommandText = sql; return Cmd.ExecuteScalar(); } catch (Exception e) { throw new Exception(e.Message, e); } finally { Close(); } } } }
    转载请注明原文地址: https://ju.6miu.com/read-1297690.html
    最新回复(0)