asp.net笔记.1
如何将数据以字符串形式输出。
首先连接数据库,vwd的项目中添加web配置文件.config为后缀。
View Code
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;
AttachDbFilename=|DataDirectory|\login.mdf;Integrated Security=True;User Instance=True"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
</system.web>
</configuration>
在<configuration>中添加<connectionStrings>内容,如代码所提示。
然后在建立一个asp,代码如下
View Code
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using System.Web.UI;
6 using System.Web.UI.WebControls;
7 using System.Data.SqlClient;
8 using System.Configuration;
9
10 public partial class connection : System.Web.UI.Page
11 {
12 protected void Page_Load(object sender, EventArgs e)
13 {
14 string sqlconnstr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
15 SqlConnection sqlconn = new SqlConnection(sqlconnstr);
16 SqlCommand sqlcommand = new SqlCommand();
17 sqlcommand.Connection = sqlconn;
18 sqlconn.Open();
19 Label1.Text = "数据库已连接上";
20 sqlcommand.CommandText = "select* from login_table";
21 SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
22 Label2.Text = "";
23 while (sqldatareader.Read())
24 {
25 Label2.Text += sqldatareader.GetInt32(0) + "";
26 Label2.Text += sqldatareader.GetString(1) + "";
27 Label2.Text += sqldatareader.GetString(2) + " <br>";
28 }
29 sqlcommand = null;
30 sqlconn.Close();
31 Label3.Text = "数据库已关闭";
32 sqlconn = null;
33
34 }
35 }