using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Web.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{ //如果不是POST提交(也就是第一次进入该页面),则初始化页面或控件等等
//!IsPostBack 非 是 post 返回
this.bind(); //获取所有数据显示在 bind控件里 //使用bind方法获取数据
}
}
public SqlConnection GetConnection() //GetConnection方法 获取链接数据库链接字符串
{
//读取 web.config <connectionStrings> 节点 name 值
string myStr = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["TimesCon"].ToString();
//创建一个新的 SQL 链接[Connection]
SqlConnection myConn = new SqlConnection(myStr);
//返回 SQL链接 字符串
return myConn;
}
protected void bind() //bind 方法
{
//实例化数据链接对象
SqlConnection myConn = GetConnection();
//打开数据库
myConn.Open();
//SQL 查询字符串
string sqlStr = "select * from tb_Student ";
//新建 SQL数据适配器
SqlDataAdapter myDa = new SqlDataAdapter(sqlStr, myConn);
//新建 数据集
DataSet myDs = new DataSet();
//SQL 数据适配器, Fill填充 到 myDs数据集中
myDa.Fill(myDs);
//GridView1.的数据源 = myDs
GridView1.DataSource = myDs;
//GridView1.的数据绑定
GridView1.DataBind();
//myDa.数据适配器 处置;释放
myDa.Dispose();
//myDs.数据集 处置;释放
myDs.Dispose();
//数据库链接.关闭
myConn.Close();
}
protected void btnSelect_Click(object sender, EventArgs e)
{
if (this.txtName.Text != "") //如果获取到的 txtName.Text 不为空
{
//实例化数据链接对象
SqlConnection myConn = GetConnection();
//打开数据库
myConn.Open();
//SQL 查询字符串
string sqlStr = "select * from tb_Student where Name=@Name";
//SQL命令 对象 新建命令 new SqlCommand(sqlStr, myConn);
SqlCommand myCmd = new SqlCommand(sqlStr, myConn);
//在myCmd.里 参数.添加("@Name",SQL Db类型.VarChar,字符长度小于20)=值 txtName.Text.Trim(去掉左右空格)
myCmd.Parameters.Add("@Name", SqlDbType.VarChar, 20).Value = this.txtName.Text.Trim();
//新建 SQL数据适配器
SqlDataAdapter myDa = new SqlDataAdapter(myCmd);
//新建 数据集
DataSet myDs = new DataSet();
//SQL 数据适配器, Fill填充 到 myDs数据集中
myDa.Fill(myDs);
if (myDs.Tables[0].Rows.Count > 0) //如果数据集行数大于0
{
//GridView1.的数据源 = myDs
GridView1.DataSource = myDs;
//GridView1.的数据绑定
GridView1.DataBind();
}
else
{
Response.Write("<script>alert('没有相关记录')</script>");
}
//myDa.数据适配器 处置;释放
myDa.Dispose();
//myDs.数据集 处置;释放
myDs.Dispose();
//数据库链接.关闭
myConn.Close();
}
else
this.bind();
}
}
C# 数据查询
最新推荐文章于 2024-08-15 09:49:33 发布