webconfig配置:

复制代码 代码如下:
<connectionStrings>
  <add name="MSSQL" connectionString="Data Source=localhost;Initial Catalog=test;User ID=sa;password=sa;" providerName="System.Data.SqlClient"/>
</connectionStrings>

前台aspx:

复制代码 代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DB.aspx.cs" Inherits="DB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>DB</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>   
        MS SQL<asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
    </div>
    </form>
</body>
</html>

后台代码:

复制代码 代码如下:
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;
    }
}

标签:
连接数据库,读取数据

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
狼山资源网 Copyright www.pvsay.com

评论“asp.net连接数据库读取数据示例分享”

暂无“asp.net连接数据库读取数据示例分享”评论...