ASP怎么连接SQL数据库?

2025-04-07 17:50:20
推荐回答(1个)
回答1:

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
using System.Data.SqlClient;     //注意需要添加此句  
  
namespace aspnet3  
{  
    public partial class datatest : System.Web.UI.Page  
    {  
        protected void Page_Load(object sender, EventArgs e)  
        {  
            string strconn = "server=localhost;uid=sa;pwd=longlt;database=School";   
            SqlConnection conn = new SqlConnection(strconn);   //创建连接   
            string sql = "select * from students";   
            conn.Open();   
            SqlCommand cmd = new SqlCommand(sql, conn);      //执行查询  
            Response.Write("连接成功");  
            SqlDataReader dr = cmd.ExecuteReader();          //查询结果  
            if (dr.Read())  
            {  
                 //利用dr[索引]对数据库表进行操作,dr[]返回object;  
                    //可以用字段做索引,也可用列号0,1..做索引  
                Response.Write(dr[0].ToString() + "
");  
            }  
  
           // this.Lab.Text = "suc";  
        }  
    }  
}

在上面的例子中,我们连接了一个sa下的School数据库,并查询了其中students字段的内容。

连接数据库分为三个步骤:先定义连接信息,再创建一个连接,最后打开连接

string strconn = "server=localhost;uid=sa;pwd=longlt;database=School";  //在这一段修改数据库的信息
SqlConnection conn = new SqlConnection(strconn);//创建连接
conn.Open();//打开连接