欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

asp.net连接数据库读取数据示例分享

程序员文章站 2024-02-27 18:21:45
webconfig配置: 复制代码 代码如下:  

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;
    }
}