using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Configuration;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Odbc;
namespace ReadXml.DB
{
public class DbHelper: IDbAction
{
private DbHelper()
{
}
enum DataProvider
{
SqlServer,OleDb,Odbc
}
private static DbHelper dbhelper;
private static object _lock = new object();
string connString = ConfigurationManager.AppSettings["DB_CONN_STR"];
public static DbHelper DBHelper
{
get
{
lock (_lock)
{
if (dbhelper == null)
{
dbhelper = new DbHelper();
}
return dbhelper;
}
}
}
/// <summary>
/// 获取数据库连接
/// </summary>
/// <param name="dp"></param>
/// <returns></returns>
private IDbConnection GetConnection(DataProvider dp)
{
switch (dp)
{
case DataProvider.SqlServer:
{
return new SqlConnection(connString);
}
case DataProvider.Odbc:
{
return new OdbcConnection(connString);
}
case DataProvider.OleDb:
{
return new OleDbConnection(connString);
}
default:
throw new Exception("xxxxxxxxxxxx");
}
}
/// <summary>
/// 打开数据库连接
/// </summary>
/// <param name="conn"></param>
private void OpenConnection(IDbConnection conn)
{
conn.Open();
}
/// <summary>
/// 数据查询
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public DataTable ExecuteQuery(string sql)
{
DataSet ds = new DataSet();
try
{
SqlConnection conn = GetConnection(DataProvider.SqlServer) as SqlConnection;
OpenConnection(conn);
SqlCommand command = new SqlCommand(sql, conn);
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
conn.Close();
}
catch (Exception e)
{
throw e;
}
return ds.Tables[0];
}
}
}
ADO。net
最新推荐文章于 2024-03-13 15:43:08 发布