目录
做法流程
按文章 第二次做结果
(与下面的显示数据不同)
1.建数据库
新建文件夹App_Data文件夹
新建数据库MyDB
新建表
表名T_User
( 点更新)
表数据
(点刷新)
2.web.config加数据库连接字符串
在左边右键数据库,点击属性(右下角显示属性)
要将数据库的属性 的连接字符串 加入到web.config中
字符串进行一定修改
<connectionStrings>
//原先的字符串
//Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Administrator\Downloads\WebApplication3\WebApplication3\WebApplication3\App_Data\MyDB.mdf;Integrated Security=True
//添加修改后的字符串
<add name="connStr" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\MyDB.mdf;Integrated Security=True"/>
</connectionStrings>
加到这
3.写web窗体
web窗体TestDB
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestDB.aspx.cs" Inherits="WebApplication3.TestDB" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvUser" runat="server"></asp:GridView>
</div>
</form>
</body>
</html>
web窗体TestDB的cs(ps:头文件后三行加上)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace WebApplication3
{
public partial class TestDB : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bind();//调用绑定方法
}
}
private void Bind()
{
string connStr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
//Response.Write(connStr);
SqlConnection conn = new SqlConnection(connStr);
conn.Open();//通过连接字符串打开数据库
SqlDataAdapter sda = new SqlDataAdapter();//实例化一个数据库适配器
//将数据库的数据塞入数据集
try
{
sda.SelectCommand = new SqlCommand();
sda.SelectCommand.Connection = conn;//把刚打开的数据库连接给他
sda.SelectCommand.CommandText = "select * from T_User where UId < 2004 ";
sda.SelectCommand.CommandType = CommandType.Text;
DataSet ds = new DataSet();
sda.Fill(ds,"T_User"); //适配器执行命令,并将所有既诶过存入到数据集里
//数据集是可以同时存入多张表的,所以我们给它起了名字叫"T_User"
gvUser.DataSource = ds.Tables["T_User"];//可用表名或数组下标去拿
gvUser.DataBind();//执行绑定
}
catch (SqlException ex)
{
//ex.Message(ex);
}
finally
{
conn.Close();
}
}
}
}
4.表不显示的部分猜测:
1.可能connstr打错。2个n。(命名自己命,我是抄老师的)
2.检查表数据有没有存进去
3.要修改连接字串
4.要改表名T_User