<!--access数据库连接方式-->
<add name="QYTangConnectionString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Test.mdb" providerName="System.Data.OleDb" />
using System;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
namespace QYTang.Gengerate
{
/// <summary>
/// OleDb操作类
/// </summary>
public abstract class OpOleDb
{
/// <summary>
/// 获取数据库查询字符串
/// </summary>
public static string connStr = ConfigurationManager.ConnectionStrings["QYTangConnectionString"].ToString();
/// <summary>
/// 根据一条sql,获取Dataset
/// </summary>
/// <param name="con">数据库连接字符串</param>
/// <param name="cmdText">sql语句</param>
/// <param name="parms">参数列表</param>
/// <returns>Dataset</returns>
public static DataSet GetDataSet(string con, string cmdText, OleDbParameter[] parms)
{
DataSet ds = new DataSet();
OleDbCommand cmd = new OleDbCommand();
OleDbConnection conn = new OleDbConnection(con);
OleDbDataAdapter da = new OleDbDataAdapter();
PrepareCommand(cmd, conn, CommandType.Text, cmdText, parms);
da.SelectCommand = cmd;
da.Fill(ds);
cmd.Parameters.Clear();
if (conn.State == ConnectionState.Open)
conn.Close();
return ds;
}
/// <summary>
/// 读取DataReader
/// </summary>
/// <param name="con">数据库连接字符串</param>
/// <param name="cmdText">sql语句</param>
/// <param name="parms">参数列表</param>
/// <returns>DataReader</returns>
public static OleDbDataReader GetDataRead(OleDbConnection conn, string cmdText, OleDbParameter[] parms)
{
OleDbCommand cmd = new OleDbCommand();
PrepareCommand(cmd, conn, CommandType.Text, cmdText, parms);
OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return dr;
}
/// <summary>
/// 插入、更新或删除操作
/// </summary>
/// <param name="con">数据库连接字符串</param>
/// <param name="cmdText">sql语句</param>
/// <param name="parms">参数列表</param>
/// <returns>接受调整的行数 </returns>
public static int Query(string con, string cmdText, OleDbParameter[] parms)
{
OleDbCommand cmd = new OleDbCommand();
OleDbConnection conn = new OleDbConnection(con);
PrepareCommand(cmd, conn, CommandType.Text, cmdText, parms);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
if (conn.State == ConnectionState.Open)
conn.Close();
return val;
}
// 为数据查询做好准备
static void PrepareCommand(OleDbCommand cmd, OleDbConnection conn, CommandType cmdType, string cmdText, OleDbParameter[] parms)
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
cmd.CommandType = cmdType;
if (parms != null)
{
for (int i = 0; i < parms.Length; i++)
cmd.Parameters.Add(parms[i]);
}
}
}
}