asp.net连接数据库读取数据示例分享
本文导语: webconfig配置: 代码如下: 前台aspx: 代码如下: DB MS SQL 后台代码: 代码如下:using System;using System.Collections.Generic;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using Syst...
webconfig配置:
前台aspx:
DB
MS SQL
后台代码:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Common;//記得要using
using System.Configuration;
public partial class DB : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataSet dsMSSQL = GetDataSet("select * from [Table]", "MSSQL");
this.GridView1.DataSource = dsMSSQL;
this.GridView1.DataBind();
}
protected DataSet GetDataSet(string SqlCommand,string DB)
{
DbProviderFactory dbProviderFactory = DbProviderFactories.GetFactory(ConfigurationManager.ConnectionStrings[DB].ProviderName);
DbConnection dbConnection = dbProviderFactory.CreateConnection();
dbConnection.ConnectionString = ConfigurationManager.ConnectionStrings[DB].ConnectionString;
DataSet ds = new DataSet();
DbCommand dbCommand = dbProviderFactory.CreateCommand();
dbCommand.Connection = dbConnection;
DbDataAdapter dbDataAdapter = dbProviderFactory.CreateDataAdapter();
dbCommand.CommandText = SqlCommand;
dbDataAdapter.SelectCommand = dbCommand;
dbDataAdapter.Fill(ds);
return ds;
}
}