ADO.NET操作数据库(查询)

Default.apsx.cs中ADO.NET操作数据库(查询数据):

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;//添加ADO.NET数据命名空间;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string strsql = "Data Source=(local);Initial Catalog=GustBook;User ID=sa;Password=sql2008@";
        SqlConnection conn= new SqlConnection(strsql);
        try
        {
            Label1.Text = "数据库连接成功";
            conn.Open();
            string sqlQuery = "select * from tbGuestBook";
            //上行查询语句,tbGuestBook是表名;
            SqlDataAdapter DataAdapter = new SqlDataAdapter(sqlQuery, conn);
            //初始化查询语句和数据库连接(conn是连接对象);
            DataSet ds = new DataSet();
            //声明数据集保存数据;
            int numbers = DataAdapter.Fill(ds, "Tables");
            //Fill方法填充数据集(其中表名可与数据库中的表相同或不同);
            for (int i = 0; i < numbers; i++)//使用循环获取数据;
            {
                Response.Write(ds.Tables["Tables"].Rows[i]["author"].ToString() + "<hr/>");
                //上行Rows中表示获取行的值和需要显示的列;
            }
        }
        catch(Exception aa)
        {
            Label1.Text = aa.ToString();
        }
    }
}

你可能感兴趣的:(sql,ADO.NET)