asp.net连接数据库读取数据示例分享
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;
}
}