背景:VisualStudio2005;
对数据库进行查询、插入、修改、删除操作;
使用GridView控件显示数据;
实现:
- 数据库设计
create database db_user
go
use db_user
go
create table tb_user
( pID varchar(10) primary key,
pName varchar(20) not null,
pSex varchar(2) not null
)
go
insert into tb_user values('1','admin','男')
go
select * from tb_user
go
go
use db_user
go
create table tb_user
( pID varchar(10) primary key,
pName varchar(20) not null,
pSex varchar(2) not null
)
go
insert into tb_user values('1','admin','男')
go
select * from tb_user
go
- 界面
- 代码
html:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="工 号:"></asp:Label>
<asp:TextBox ID="txtPID" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="txtPID"
ErrorMessage="用户已经存在!" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
<asp:CheckBox ID="chkPID" runat="server" Style="z-index: 100; left: 353px; position: absolute;
top: 15px" />
<br />
<asp:Label ID="Label2" runat="server" Text="姓 名:"></asp:Label>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtName"
ErrorMessage="*"></asp:RequiredFieldValidator>
<asp:CheckBox ID="chkPName" runat="server" Style="z-index: 101; left: 353px; position: absolute;
top: 39px" />
<br />
<asp:Label ID="Label3" runat="server" Text="性 别:"></asp:Label>
<asp:RadioButton ID="rbtMale" runat="server" GroupName="sex" Text="男" Width="43px" Checked="True" />
<asp:RadioButton ID="rbtFemale" runat="server" GroupName="sex" Text="女" />
<asp:CheckBox ID="chkPSex" runat="server" Style="z-index: 103; left: 353px; position: absolute;
top: 63px" />
<br />
<asp:Button ID="btnAdd" runat="server" OnClick="btnAdd_Click" Text="添 加" />
<asp:Button ID="btnDelete" runat="server" Text="删 除" CausesValidation="False" OnClick="btnDelete_Click" />
<asp:Button ID="btnEdit" runat="server" Text="修 改" CausesValidation="False" OnClick="btnEdit_Click" />
<asp:Button ID="btnSelect" runat="server" Text="查 询" CausesValidation="False" OnClick="btnSelect_Click" />
<br />
<asp:Label ID="lblMessage" runat="server" Width="240px"></asp:Label><br />
<asp:GridView ID="GridView1" runat="server" Height="137px" Width="240px" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" >
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:BoundField DataField="pID" HeaderText="工 号" />
<asp:BoundField DataField="pName" HeaderText="姓 名" />
<asp:BoundField DataField="pSex" HeaderText="性 别" />
</Columns>
<RowStyle BackColor="#EFF3FB" Font-Size="Small" HorizontalAlign="Center" />
<EditRowStyle BackColor="#2461BF" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" Font-Size="Small" ForeColor="White"
HorizontalAlign="Center" />
<AlternatingRowStyle BackColor="White" HorizontalAlign="Center" />
</asp:GridView>
</div>
</form>
</body>
</html>
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="工 号:"></asp:Label>
<asp:TextBox ID="txtPID" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="txtPID"
ErrorMessage="用户已经存在!" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
<asp:CheckBox ID="chkPID" runat="server" Style="z-index: 100; left: 353px; position: absolute;
top: 15px" />
<br />
<asp:Label ID="Label2" runat="server" Text="姓 名:"></asp:Label>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtName"
ErrorMessage="*"></asp:RequiredFieldValidator>
<asp:CheckBox ID="chkPName" runat="server" Style="z-index: 101; left: 353px; position: absolute;
top: 39px" />
<br />
<asp:Label ID="Label3" runat="server" Text="性 别:"></asp:Label>
<asp:RadioButton ID="rbtMale" runat="server" GroupName="sex" Text="男" Width="43px" Checked="True" />
<asp:RadioButton ID="rbtFemale" runat="server" GroupName="sex" Text="女" />
<asp:CheckBox ID="chkPSex" runat="server" Style="z-index: 103; left: 353px; position: absolute;
top: 63px" />
<br />
<asp:Button ID="btnAdd" runat="server" OnClick="btnAdd_Click" Text="添 加" />
<asp:Button ID="btnDelete" runat="server" Text="删 除" CausesValidation="False" OnClick="btnDelete_Click" />
<asp:Button ID="btnEdit" runat="server" Text="修 改" CausesValidation="False" OnClick="btnEdit_Click" />
<asp:Button ID="btnSelect" runat="server" Text="查 询" CausesValidation="False" OnClick="btnSelect_Click" />
<br />
<asp:Label ID="lblMessage" runat="server" Width="240px"></asp:Label><br />
<asp:GridView ID="GridView1" runat="server" Height="137px" Width="240px" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" >
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:BoundField DataField="pID" HeaderText="工 号" />
<asp:BoundField DataField="pName" HeaderText="姓 名" />
<asp:BoundField DataField="pSex" HeaderText="性 别" />
</Columns>
<RowStyle BackColor="#EFF3FB" Font-Size="Small" HorizontalAlign="Center" />
<EditRowStyle BackColor="#2461BF" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" Font-Size="Small" ForeColor="White"
HorizontalAlign="Center" />
<AlternatingRowStyle BackColor="White" HorizontalAlign="Center" />
</asp:GridView>
</div>
</form>
</body>
</html>
后台:
person.cs:
public class person
{
//定义person对象的三个属性字段
public string pID;
public string pName;
public string pSex;
public person()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
}
{
//定义person对象的三个属性字段
public string pID;
public string pName;
public string pSex;
public person()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
}
personOperate.cs:
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.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;
/// <summary>
/// operate 的摘要说明,所有操作类
/// </summary>
public class personOperate
{
public personOperate()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public static SqlConnection createCon()
{
return new SqlConnection("server=localhost\\sqlexpress;database=db_user;uid=sa;pwd=hello");
}
/// operate 的摘要说明,所有操作类
/// </summary>
public class personOperate
{
public personOperate()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public static SqlConnection createCon()
{
return new SqlConnection("server=localhost\\sqlexpress;database=db_user;uid=sa;pwd=hello");
}
//根据员工工号 pID查询数据库是否已经存在同名记录
public static bool findPerson( string pID)
{
SqlConnection con = personOperate.createCon();
con.Open();
SqlCommand cmd = new SqlCommand("select count(*) from tb_user where pID='" + pID + "'", con);
//用count获取:返回查询所返回的结果集中的第一行第一列;如果大于0表示存在记录;反之则不存在
int count = Convert.ToInt32(cmd.ExecuteScalar());
if (count > 0)
{
return true;
}
else
{
return false;
}
}
//显示所有员工信息
public static DataTable selectAll()
{
SqlConnection con = personOperate.createCon();
//SqlDataApapter表示用于填充DataSet和更新SQL Server数据库的一组数据命令和一个数据库连接
SqlDataAdapter sda = new SqlDataAdapter();
//(获取或)设置一个T_SQL语句或存储过程,用于在数据源中选择记录
sda.SelectCommand = new SqlCommand("select * from tb_user", con);
//DataSet表示数据在内存中的缓存;初始化DataSet类的新实例
DataSet ds = new DataSet();
//使用sda.Fill()方法填充ds,并创建一个名为“user"的DataTable对象,将数据存放在表中
sda.Fill(ds, "user");
//(获取或)设置在DataSet中的表的集合
//获取数据集中的数据表
return ds.Tables["user"];
}
//添加员工数据,添加时检查员工工号字段pID是否已经存在
public static bool addPerson(person p)
{
try
{
SqlConnection con = personOperate.createCon();
con.Open();
SqlCommand cmd = new SqlCommand("insert into tb_user values(@pID,@pName,@pSex)", con);
SqlParameter para = new SqlParameter("@pID", SqlDbType.VarChar, 10);
para.Value = p.pID;
cmd.Parameters.Add(para);
para = new SqlParameter("@pName", SqlDbType.VarChar, 20);
para.Value = p.pName;
cmd.Parameters.Add(para);
para = new SqlParameter("@pSex", SqlDbType.VarChar, 2);
para.Value = p.pSex;
cmd.Parameters.Add(para);
cmd.ExecuteNonQuery();
return true;
}
catch (Exception e)
{
return false;
}
}
//根据员工工号pID删除员工数据
public static bool delPerson(string pID)
{
try
{
SqlConnection con = personOperate.createCon();
con.Open();
//表示要对SQL Server数据库执行一个T_SQL语句或存储过程,在此使用参数
SqlCommand cmd = new SqlCommand("delete from tb_user where pID='" + @pID + "'", con);
//表示SqlCommand的参数(参数名称,数据类型,大小)
SqlParameter para = new SqlParameter("@pID", SqlDbType.VarChar, 10);
//(获取或)设置参数的值
para.Value = pID;
//将制定的SqlParameter对象添加到SqlParameterCollection中
cmd.Parameters.Add(para);
//对连接执行T_SQL语句并返回受影响的行数
cmd.ExecuteNonQuery();
return true;
}
catch (Exception e)
{
return false;
}
}
catch (Exception e)
{
return false;
}
}
//根据员工工号pID修改员工数据
public static bool editPerson(person p)
{
try
{
SqlConnection con = personOperate.createCon();
con.Open();
SqlCommand cmd = new SqlCommand("update tb_user set pName='"+p.pName+ "',pSex='" + p.pSex + "' where pID='" +p.pID+"'", con);
cmd.ExecuteNonQuery();
return true;
}
catch (Exception eedit)
{
return false;
}
}
//根据条件模糊查询用户信息
public static DataTable selectPerson(string sql)
{
SqlConnection con = personOperate.createCon();
con.Open();
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = new SqlCommand(sql, con);
DataSet ds = new DataSet();
sda.Fill(ds, "user");
return ds.Tables["user"];
}
}
Default.aspx:
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.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;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//初始化页面时,读取全部用户信息
this.fillGV();
}
}
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//初始化页面时,读取全部用户信息
this.fillGV();
}
}
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
//获取需自定义验证控件验证的值
string pID = args.Value;
//调用personOperate.findPerson()函数
if(personOperate.findPerson(pID))
{
args.IsValid=false;
}
else
{
args.IsValid=true;
}
}
//将GridView1数据源设置为DataTable表数据
private void fillGV()
{
this.GridView1.DataSource=personOperate.selectAll();
this.GridView1.DataBind();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
//如果页面通过验证,则引发添加数据的按钮事件
if (this.IsValid)
{
//实例化person对象
person p = new person();
p.pID = this.txtPID.Text;
p.pName = this.txtName.Text;
if (this.rbtMale.Checked)
{
p.pSex = "男";
}
else
{
p.pSex = "女";
}
//如果用户不存在则调用personOperate.delPerson()方法进行用户信息添加
if (personOperate.addPerson(p))
{
this.lblMessage.Text = "插入成功!";
this.fillGV();
{
//如果页面通过验证,则引发添加数据的按钮事件
if (this.IsValid)
{
//实例化person对象
person p = new person();
p.pID = this.txtPID.Text;
p.pName = this.txtName.Text;
if (this.rbtMale.Checked)
{
p.pSex = "男";
}
else
{
p.pSex = "女";
}
//如果用户不存在则调用personOperate.delPerson()方法进行用户信息添加
if (personOperate.addPerson(p))
{
this.lblMessage.Text = "插入成功!";
this.fillGV();
}
else
{
this.lblMessage.Text = "插入失败!";
}
}
}
else
{
this.lblMessage.Text = "插入失败!";
}
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
//获取用户的工号字段值pID,并调用personOperate.delPerson()方法删除指定用户信息
string pID = this.txtPID.Text;
if (personOperate.delPerson(pID))
{
this.lblMessage.Text = "删除成功!";
this.fillGV();
}
else
{
this.lblMessage.Text = "删除失败!";
}
}
//根据员工工号修改员工信息
protected void btnEdit_Click(object sender, EventArgs e)
{
person p = new person();
p.pID = this.txtPID.Text;
p.pName = this.txtName.Text;
if (this.rbtMale.Checked)
{
p.pSex = "男";
}
else
{
p.pSex = "女";
}
if (personOperate.editPerson(p))
{
this.lblMessage.Text = "修改成功!";
this.fillGV();
}
else
{
this.lblMessage.Text = "修改失败!";
}
}
else
{
this.lblMessage.Text = "修改失败!";
}
}
protected void btnSelect_Click(object sender, EventArgs e)
{
//初始设置查询字符串,使用"where 1=1"
string sqlQuery = "select * from tb_user where 1=1 ";
if (this.chkPID.Checked)
{
sqlQuery = sqlQuery + " and"+" pID like '%"+ this.txtPID.Text +"%'";
}
if (this.chkPName.Checked)
{
sqlQuery = sqlQuery + " and" + " pName like '%" + this.txtName.Text + "%'";
}
if (this.chkPSex.Checked && this.rbtMale.Checked)
{
sqlQuery += " and" + " pSex='" + "男" + "'";
}
if (this.chkPSex.Checked && this.rbtFemale.Checked)
{
sqlQuery += " and" + " pSex='" + "女" + "'";
}
//SqlConnection con = personOperate.createCon();
//con.Open();
//SqlDataAdapter sda = new SqlDataAdapter();
//sda.SelectCommand = new SqlCommand(sqlQuery, con);
//DataSet ds = new DataSet();
//sda.Fill(ds, "user");
//this.GridView1.DataSource = ds.Tables["user"];
//this.GridView1.DataBind();
this.GridView1.DataSource = personOperate.selectPerson(sqlQuery);
this.GridView1.DataBind();
if (this.chkPSex.Checked && this.rbtMale.Checked)
{
sqlQuery += " and" + " pSex='" + "男" + "'";
}
if (this.chkPSex.Checked && this.rbtFemale.Checked)
{
sqlQuery += " and" + " pSex='" + "女" + "'";
}
//SqlConnection con = personOperate.createCon();
//con.Open();
//SqlDataAdapter sda = new SqlDataAdapter();
//sda.SelectCommand = new SqlCommand(sqlQuery, con);
//DataSet ds = new DataSet();
//sda.Fill(ds, "user");
//this.GridView1.DataSource = ds.Tables["user"];
//this.GridView1.DataBind();
this.GridView1.DataSource = personOperate.selectPerson(sqlQuery);
this.GridView1.DataBind();
}
}
}
- 运行
1、首次加载页面,显示所有员工信息
2、添加用户信息,提示“插入成功”
3、将新添加记录的员工性别有“男”更改为“女”
4、删除员工号为12的用户记录
5、查询工号中包含有“1”的员工信息
6、查询员工姓名中包含有“阳”的员工记录
7、查询性别为男的所有员工信息
8、精确查询
转载于:https://blog.51cto.com/hndtraveller/172801