asp.net连接数据库读取数据示例分享
时间:2024-01-23 11:45:19
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;
}
}
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
k8s在go语言中的使用及client 初始化简介
golang与pgsql交互的实现
![](https://img.aspxhome.com/file/2023/4/123954_0s.png)
在python里协程使用同步锁Lock的实例
MySQL常用命令与内部组件及SQL优化详情
![](https://img.aspxhome.com/file/2023/1/111381_0s.png)
ASP连接MSSQL的错误: 拒绝访问
Python Socket TCP双端聊天功能实现过程详解
python中的global关键字的使用方法
MySQL数据库的其它安全问题
用python做个代码版的小仙女蹦迪视频
![](https://img.aspxhome.com/file/2023/5/115715_0s.jpg)
Python匿名函数/排序函数/过滤函数/映射函数/递归/二分法
在Django中URL正则表达式匹配的方法
![](https://img.aspxhome.com/file/2023/2/94012_0s.jpg)
Python中的测试模块unittest和doctest的使用教程
Python实现微信翻译机器人的方法
![](https://img.aspxhome.com/file/2023/7/64337_0s.jpg)
Python实现功能完整的个人员管理程序
![](https://img.aspxhome.com/file/2023/1/131061_0s.png)
超详细Python解释器新手安装教程
![](https://img.aspxhome.com/file/2023/0/103010_0s.png)
sql 判断函数、存储过程是否存在的代码整理
自己动手用Golang实现约瑟夫环算法的示例
![](https://img.aspxhome.com/file/2023/6/134316_0s.png)
Python实现Excel自动分组合并单元格
![](https://img.aspxhome.com/file/2023/5/87915_0s.jpg)
IPython 8.0 Python 命令行交互工具
![](https://img.aspxhome.com/file/2023/0/87720_0s.png)