当前位置: 代码迷 >> ASP.NET >> DBHelper 使用有关问题
  详细解决方案

DBHelper 使用有关问题

热度:10237   发布时间:2013-02-25 00:00:00.0
DBHelper 使用问题
新手,莫见笑。我想 用dbhelper 实现操作数据库的类,然后default页面调用这个类 
webconfig 代码 是  
  <appSettings/>
  <connectionStrings>
  <add name="NorthwindConnectionString" connectionString="server=.;DataBase=xin;uid=sa;pwd=123;" providerName="System.Data.SqlClient" />
  </connectionStrings>


dbhelper的代码是从别人项目里直接粘贴过来的,dbhelper的代码太长,我删除掉了后面的一部分。我不知道怎么使用

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Odbc;
using System.Data.Common;


namespace SQLServerDAL
{
  /// <summary>
  /// 用来创建DataBase对象的静态类
  /// </summary>
  public static class DBHelper
  {
  public static DataBase CreateData(string DataNameInConfigfile)
  {
  string pn = ConfigurationManager.ConnectionStrings[DataNameInConfigfile].ProviderName; //读取配置文件
  string cs = ConfigurationManager.ConnectionStrings[DataNameInConfigfile].ConnectionString;

  //下面判断数据库类型并创建相应的对象

  if (pn.ToUpper().Contains("OLEDB"))
  {
  OleDbDataAdapter oledbda = new OleDbDataAdapter();
  oledbda.SelectCommand = new OleDbCommand();
  oledbda.SelectCommand.Connection = new OleDbConnection(cs);
  return new DataBase(oledbda);
  }
  if (pn.ToUpper().Contains("SQL"))
  {
  SqlDataAdapter sqlda = new SqlDataAdapter();
  sqlda.SelectCommand = new SqlCommand();
  sqlda.SelectCommand.Connection = new SqlConnection(cs);
  return new DataBase(sqlda);
  }
  if (pn.ToUpper().Contains("ODBC"))
  {
  OdbcDataAdapter odbcda = new OdbcDataAdapter();
  odbcda.SelectCommand = new OdbcCommand();
  odbcda.SelectCommand.Connection = new OdbcConnection(cs);
  return new DataBase(odbcda);
  }
  return null;
  }

  public static DataBase CreateData(string ConnectionString, string ProviderName)
  {
  //以下判断数据库类型并创建相应的对象
  if (ProviderName.ToUpper().Contains("OLEDB"))
  {
  OleDbDataAdapter oledbda = new OleDbDataAdapter();
  oledbda.SelectCommand = new OleDbCommand();
  oledbda.SelectCommand.Connection = new OleDbConnection(ConnectionString);
  return new DataBase(oledbda);
  }
  if (ProviderName.ToUpper().Contains("SQL"))
  {
  SqlDataAdapter sqlda = new SqlDataAdapter();
  sqlda.SelectCommand = new SqlCommand();
  sqlda.SelectCommand.Connection = new SqlConnection(ConnectionString);
  return new DataBase(sqlda);
  }
  if (ProviderName.ToUpper().Contains("ODBC"))
  {
  OdbcDataAdapter odbcda = new OdbcDataAdapter();
  odbcda.SelectCommand = new OdbcCommand();
  odbcda.SelectCommand.Connection = new OdbcConnection(ConnectionString);
  return new DataBase(odbcda);
  }
  return null;