环境:ASP.NET.WEB(C#)
要求
使用SqlCommand对象查询数据库中的记录。
执行程序,在文本框中输入“张三”,单机查询控件,将会在界面上显示查询结果。
步骤
1.在Default.aspx中添加控件
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SqlCommand1.WebForm1" %>
<!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:Label ID="Label1" runat="server" Text="请输入姓名"></asp:Label>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:Button ID="btnSelect" OnClick="btnSelect_Click" runat="server" Text="查询" />
<asp:GridView ID="gvStudent" runat="server"></asp:GridView>
</div>
</form>
</body>
</html>
2.配置数据库
我使用了sql server的SC数据库,登录名sa,密码123456,根据自己的数据库实际情况而定
Web.config
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add providerName="System.Data.SqlClient" connectionString="server=.;database=SC;uid=sa;pwd=123456" name="sqlconn"/>
</connectionStrings>
<system.web>
<compilation debug="true"/>
</system.web>
</configuration>
3.连接数据库并进行数据绑定
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace SqlCommand1
{
public partial class WebForm1 : System.Web.UI.Page
{
public SqlConnection GetConnection()
{
//获取web.config 中连接字符串
string myStr = System.Configuration.ConfigurationManager.
ConnectionStrings["sqlconn"].ToString();
SqlConnection myConn = new SqlConnection(myStr);
return myConn;
}
protected void btnSelect_Click(object sender,EventArgs e)
{
BindStudent();//调用数据绑定函数
}
public void BindStudent()
{
SqlConnection myConn = GetConnection();
myConn.Open();
string name = txtName.Text.ToString().Trim();//获取文本框内容,学生信息
string sqlStr = "select * from Students where sname='" + name + "'";//SQL查询语句
SqlCommand myCmd = new SqlCommand(sqlStr, myConn);
SqlDataAdapter myDa = new SqlDataAdapter(myCmd);
DataSet myDs = new DataSet();
myDa.Fill(myDs);
if(myDs.Tables[0].Rows.Count>0)
{
gvStudent.DataSource = myDs;
gvStudent.DataBind();
}
else
{
Response.Write("<script>alert('没有相关记录')</script>");
}
myDa.Dispose();
myDs.Dispose();
myConn.Close();
}
}
}