在ASP.NET中,进行数据库的查询,添加,删除,修改操作
在网页中使用GridView进行数据库表单的显示,以及基本的数据库操作,SqlCommand和SqlDataAdapter
查询功能,插入数据功能:(在Textbox中输入内容,点击按钮执行查询插入功能)
webForm源码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="ADOTest.WebForm1" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>title>
<style type="text/css">
#Password {
width: 100px;
}
#Password_confirm {
width: 100px;
}
style>
head>
<body>
<form style="text-align:center" id="form1" runat="server">
<div style="text-align:center; font-size: large; color: #000000;">
<div style="text-align:center" >
用户名查询
<asp:TextBox ID="TextBoxSelect" runat="server">asp:TextBox>
<asp:Button ID="Btn_select" runat="server" OnClick="Btn_select_Click" Text="查询" />
div>
<hr />
<asp:GridView ID="GridView2" runat="server" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" OnRowCancelingEdit="GridView2_RowCancelingEdit" OnRowDeleting="GridView2_RowDeleting" OnRowEditing="GridView2_RowEditing" OnRowUpdating="GridView2_RowUpdating" CellPadding="8" CellSpacing="4" ForeColor="#333333" HorizontalAlign="Center" Width="420px">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" HorizontalAlign="Center" VerticalAlign="Middle" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" HorizontalAlign="Center" VerticalAlign="Middle" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" VerticalAlign="Middle" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" HorizontalAlign="Center" VerticalAlign="Middle" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
asp:GridView>
<hr />
输入ID:<asp:TextBox ID="TextBoxID" runat="server" Width="60px">asp:TextBox>
用户名:<asp:TextBox ID="TextBoxUserName" runat="server" Width="100px">asp:TextBox>
密码:<input runat="server" id="Password" type="password" />确认密码:<input runat="server" id="Password_confirm" type="password" /><asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="添加" />
div>
form>
body>
html>
后台功能源码
///
/// bing()方法,读取数据库的数据,并将其绑定到数据控件GridView中
///
///
///
protected void bind()
{
SqlConnection myConn = new SqlConnection("Data Source=WIN8;Initial Catalog=SqlDataTest01;Persist Security Info=True;User ID=sa;Password=123456");
myConn.Open();
string sqlStr = "select * from UserTable order by ID ";
SqlDataAdapter myDa = new SqlDataAdapter(sqlStr, myConn);
DataSet myDs = new DataSet();
myDa.Fill(myDs);
GridView2.DataSource = myDs;
GridView2.DataKeyNames = new string[] { "ID" };
GridView2.DataBind();
myDa.Dispose();
myDs.Dispose();
myConn.Close();
}
//插入数据
protected void Button2_Click(object sender, EventArgs e)
{
if (this.TextBoxID.Text!=""&&this.TextBoxUserName.Text != "" && this.Password.Value!="" && Password.Value==Password_confirm.Value)
{
SqlConnection myConn = new SqlConnection("Data Source=WIN8;Initial Catalog=SqlDataTest01;Persist Security Info=True;User ID=sa;Password=123456");
myConn.Open();
string sqlStr = "insert into UserTable values ('" + this.TextBoxID.Text.Trim() + "','" + this.TextBoxUserName.Text.Trim() + "','" + this.Password.Value + "')";
SqlCommand myCmd = new SqlCommand(sqlStr,myConn);
myCmd.ExecuteNonQuery();
myConn.Close();
this.bind();
}
else
{
Response.Write("");
}
}
//查询功能
protected void Btn_select_Click(object sender, EventArgs e)
{
if (this.TextBoxSelect.Text != "") //判断输入框是否为空
{
//与数据库进行连接
SqlConnection myConn = new SqlConnection("Data Source=WIN8;Initial Catalog=SqlDataTest01;Persist Security Info=True;User ID=sa;Password=123456");
myConn.Open();
//查询操作
string sqlStr = "select * from UserTable where UserName=@UserName";
SqlCommand myCmd = new SqlCommand(sqlStr, myConn);
myCmd.Parameters.Add("@UserName", SqlDbType.VarChar, 50).Value = this.TextBoxSelect.Text.Trim();
SqlDataAdapter myDa = new SqlDataAdapter(myCmd);
//将查询的结果添加到DataSet中
DataSet myDs = new DataSet();
myDa.Fill(myDs);
//在GridView中显示查询到的结果
if (myDs.Tables[0].Rows.Count > 0)
{
GridView2.DataSource = myDs;
GridView2.DataBind();
}
else
{
Response.Write("");
this.bind();
}
myDa.Dispose();
myDs.Dispose();
myConn.Close();
}
else
{
Response.Write("");
}
}
删除功能,更新:(在GridView属性事件中进行数据删除操作)
protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
// string userN =GridView2.DataKeys[e.RowIndex].Value.ToString();
//获取删除字段所在行的关键字段的值
int userid = Convert.ToInt32(GridView2.DataKeys[e.RowIndex].Value);
string sqlStr = "delete from UserTable where ID= "+userid;
SqlConnection myConn = new SqlConnection("Data Source=WIN8;Initial Catalog=SqlDataTest01;Persist Security Info=True;User ID=sa;Password=123456");
myConn.Open();
SqlCommand myCmd = new SqlCommand(sqlStr, myConn);
myCmd.ExecuteNonQuery();
myCmd.Dispose();
myConn.Close();
GridView2.EditIndex = -1;
this.bind();
}
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
((LinkButton)e.Row.Cells[0].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('确认删除:\"" + e.Row.Cells[1].Text + "\"吗?')");
//((LinkButton)e.Row.Cells[1].Controls[0]).Attributes.Add("onclick", "return confirm('确定要删除吗?')");
}
}
protected void GridView2_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView2.EditIndex = e.NewEditIndex;
this.bind();
}
protected void GridView2_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//更新操作时会对页面进行刷新
int userid = Convert.ToInt32(GridView2.DataKeys[e.RowIndex].Value);
string UName = ((TextBox)(GridView2.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString();
string PWord = ((TextBox)(GridView2.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString();
string sqlStr = "update UserTable set UserName='"+UName+ "',PassWord='" +PWord+ "' where ID =" + userid;
SqlConnection myConn = new SqlConnection("Data Source=WIN8;Initial Catalog=SqlDataTest01;Persist Security Info=True;User ID=sa;Password=123456");
myConn.Open();
SqlCommand myCmd = new SqlCommand(sqlStr, myConn);
myCmd.ExecuteNonQuery();
myCmd.Dispose();
myConn.Close();
GridView2.EditIndex = -1;
this.bind();
}
protected void GridView2_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView2.EditIndex = -1;
this.bind();
}
在查询操作中:
myCmd.Parameters.Add(“@UserName”, SqlDbType.VarChar, 50).Value = this.TextBox1.Text.Trim();
这一句实现将输入框中的值传递到数据库中的UserName参数中;
其中Parameters.Add()是 将 System.Data.SqlClient.SqlParameter 及其参数名、数据类型和列宽添加到System.Data.SqlClient.SqlParameterCollection;
Trim()方法是 从当前 System.String 对象移除所有前导空白字符和尾部空白字符。
在删除数据操作中:
int userid = Convert.ToInt32(GridView2.DataKeys[e.RowIndex].Value);
定义userid是获取该删除行所在的主键值,其中【GridViewDeleteEventArgs 】e.RowIndex的值就是该事件对象所在行的索引值,DataKeys.Valuequ了该行的主键值
在更新操作中:
string UName = ((TextBox)(GridView2.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString();
定义UName是将单元格转换成输入框再获取其中的值,获取索引中第2格单元格中的索引值为0的控件,官方对Controls的解释为获取表示一个指定的服务器控件的子控件在 UI 层次结构的 System.Web.UI.ControlCollection 对象。返回 子控件的集合指定的服务器控件的。(不明白Controls[0]在这里所表示的含义,[0]表示的是控件)
(过程中遇到在数据框汇总输入完后,点击更新后并为进行数据的更新,【解决方法】由于页面在点击操作是会对页面进行刷新,没有获取到新的输入值,需要在Page_Load函数中,增加判断语句 if(!IsPostBack))
其中 IsPostBack判断该页是第一次呈现还是为了响应回发而加载,如果是为响应客户端回发而加载该页则为true
在插入操作中:
myCmd.ExecuteNonQuery();
ExcuteNonQuery()是对连接执行 Transact-SQL 语句并返回受影响的行数
以上就是使用ADO.NET进行数据的简单的增删查改操作