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;
}
}
相关文章
密码绑定至密码文本框中(TextMode设为Password)
一般情况之下TextBox的TextMode设为Password话,我们想在后台(.cs)绑定一个值至此文本框,是无法实现的,如果一定要绑定值的话,该如何实现呢?,本文将告诉你实现方法,感兴趣的朋友可以参考下2013-01-01asp.net中Session缓存与Cache缓存的区别分析
实现数据的缓存有很多种方法,有客户端的Cookie,有服务器端的Session和Application2013-02-02ASP.NET Core2读写InfluxDB时序数据库的方法教程
Influxdb是一个开源的分布式时序、时间和指标数据库,使用go语言编写,无需外部依赖,下面这篇文章主要给大家介绍了关于ASP.NET Core2读写InfluxDB时序数据库的相关资料,需要的朋友可以参考下2018-11-11
最新评论