public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataLoad();
}
}
private void DataLoad()
{
DbConnection conn = GetCon();
DbCommand cmd = conn.CreateCommand();
/*string sqlstr = "insert into T_User(Id,UserName,Password,Mobile) values(@id,@username,@password,@mobile)";
if (conn.GetType() == typeof(OracleConnection
))
{
sqlstr.Replace('@', ':');
}*/
cmd.CommandText = "select * from T_User";
DataTable dt = new DataTable();
DbDataAdapter adapter = GetDataadpter();
adapter.SelectCommand = cmd;
adapter.Fill(dt);
cmd.Dispose();
conn.Dispose();
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}
//根据选择的数据库动态返回数据适配器
private DbDataAdapter GetDataadpter()
{
DbDataAdapter adapter = null;
//string content = File.ReadAllText(@"c:\conncetion.txt");
string content = ConfigurationManager.AppSettings["data"];
if (content.ToUpper() == "SQLSERVER")
{
adapter = new SqlDataAdapter();
}
else if (content.ToUpper() == "ORACLE")
{
adapter = new OracleDataAdapter();
}
return adapter;
}
//根据选择的数据库动态返回连接对象
private DbConnection GetCon()
{
string strcon = "";
DbConnection con = null;
//string content = File.ReadAllText(@"c:\conncetion.txt");
string content = ConfigurationManager.AppSettings["data"];//使用appsettings
if (content.ToUpper() == "SQLSERVER")
{
strcon = ConfigurationManager.ConnectionStrings["sqlservercon"].ConnectionString;
con = new SqlConnection(strcon);
}
else if (content.ToUpper() == "ORACLE")
{
strcon = ConfigurationManager.ConnectionStrings["oraclecon"].ConnectionString; ;
con = new OracleConnection(strcon);
}
return con;
}
}
///config
<appSettings>
<add key="data" value="SQLSERVER(oracle)"/>
</appSettings>
<connectionStrings>
<add name="sqlservercon" connectionString="Data Source=Y-PC;Initial Catalog=MyTest;Persist Security Info=True;User ID=sa;Password=y@163"/>
<add name="oraclecon" connectionString="Data Source=orcl;Persist Security Info=True;User ID=yzc;Password=sa;Unicode=True" providerName="System.Data.OracleClient"/>
</connectionStrings>