ASP.net+SQL server2008简单的数据库增删改查 VS2012
工具:VS2012
数据库:SQL server
简单说明:根据老师上课给的代码,进行了简单的改正适用于VS2012环境,包括注册、登录、查询、修改、删除功能,多数参考了网上的代码
百度云源代码连接testDAO:http://pan.baidu.com/s/1c0CTRgs
遇见的问题:
1、字符文本中字符太多: 在html中用的<a href=" ">,在.NET中需要把双引号变成单引号,javascript中的部分双引号也需变成单引号,此处代码详见register.aspx
2、如何javascript获取表格中的行数:通过varx=document.getElementById("表格id");找到table,x.rows[].cells[]即可找到第几行第几列 此处代码详见register.aspx的javascript代码
3、如何通过asp获取url中参数的值:http://localhost:30965/testDAO/list.aspx?username=16&psaaword=21
String x= Request.QueryString["username"];即可获得username的值16
文件结构如右图所示
数据库名字:easylife 表的名字:table_user 表内容如图:
界面如下图所示:
DBHelper.cs代码:在每一个对象的数据库访问类中:1、数据库连接反复出现 2、数据库连接打开和关闭反复出现 3、执行Sql语句的方法相似
因此,定义DBHelper类,封装常用的方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient; /// <summary>
/// DBHelper 的摘要说明
/// </summary>
namespace testDAO.Library
{
public class DBHelper
{//server=.;Trusted_Connection=SSPI;database=easylife
private String connectionString = "server=.;database=easylife;uid=sa;pwd=root"; public SqlDataReader ExecuteReader(String sql)
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open(); SqlCommand command = new SqlCommand(sql,connection); SqlDataReader result = command.ExecuteReader(); return result;
} public bool ExecuteCommand(String sql)
{
bool result = false; try
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open(); SqlCommand command = new SqlCommand(sql,connection);
//command.Connection = connection;
//command.CommandText = sql;
command.ExecuteNonQuery(); connection.Close(); result = true;
}
catch (Exception e)
{
throw e;
} return result;
} }
}
定义User类封装用户信息 User.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; /// <summary>
/// User 的摘要说明
/// </summary>
namespace testDAO.Library
{
public class User
{
private String userName = "";
private String userLogin = "";
private String userPwd = ""; public String UserName
{
get
{
return userName;
}
set
{
userName = value;
}
} public String UserLogin
{
get
{
return userLogin;
}
set
{
userLogin = value;
}
} public String UserPwd
{
get
{
return userPwd;
}
set
{
userPwd = value;
}
}
}
}
采用UserService实现将用户信息的数据库操作 UserService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; using System.Data.SqlClient;
/// <summary>
/// UserService 的摘要说明
/// </summary>
namespace testDAO.Library
{
public class UserService
{
public bool AddUser(User user)
{
bool result = false;
String sql = ""; sql = "insert into table_user (userName,userLogin,userPwd)values(";
sql += "'" + user.UserName + "',";
sql += "'" + user.UserLogin + "',";
sql += "'" + user.UserPwd + "'";
sql += ")"; DBHelper helper = new DBHelper();
result = helper.ExecuteCommand(sql);
return result; } public User GetUserByLogin(User user)
{
String sql = ""; sql = "select * from table_user where userLogin='" + user.UserLogin + "'"; DBHelper helper = new DBHelper();
SqlDataReader reader = helper.ExecuteReader(sql);
User result = new User();
if (reader.Read())
{ result.UserName = reader.GetString();
result.UserLogin = reader.GetString();
result.UserPwd = reader.GetString(); }
else
{
return null;
} return result;
} public List<User> GetAllUsers()
{
String sql = ""; sql = "select * from table_user"; DBHelper helper = new DBHelper();
SqlDataReader reader = helper.ExecuteReader(sql); if (!reader.HasRows)
{
return null;
} List<User> list = new List<User>();
while (reader.Read())
{
User item = new User(); item.UserName = reader.GetString();
item.UserLogin = reader.GetString();
item.UserPwd = reader.GetString(); list.Add(item);
} return list;
} public bool DeleteUsers(String i)
{
bool result = false;
String sql = "";
sql = "delete from table_user where userLogin ='"+ i+" '" ;
DBHelper helper = new DBHelper();
result = helper.ExecuteCommand(sql);
return result;
} public bool UpdateUsers(User user)
{
bool result = false;
String sql = "";
sql = "update table_user set userName= '" + user.UserName + "',userPwd='" + user.UserPwd + " ' where userlogin='" + user.UserLogin + " '";
// update table_user set userName='1',userPwd='1' where userLogin='5'
DBHelper helper = new DBHelper();
result = helper.ExecuteCommand(sql);
return result;
} }
}
业务逻辑层UserManager.cs,是表示层与数据访问层的桥梁 ,用于完成逻辑判断、业务处理、数据传递等操作。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; /// <summary>
/// UserManager 的摘要说明
/// </summary>
namespace testDAO.Library
{
public class UserManager
{
public bool AddUser(User user)
{
UserService service = new UserService();
User temp = service.GetUserByLogin(user); if (temp != null)
{
return false;
} bool result = service.AddUser(user);
return result;
} public bool Login(User user)
{
bool result = false; UserService service = new UserService(); User temp = service.GetUserByLogin(user);
if (temp == null)
{
result = false;
}
else if (user.UserPwd.Equals(temp.UserPwd))
{
result = true;
} return result;
} public List<User> GetAllUsers()
{
UserService service = new UserService();
return service.GetAllUsers();
}
public bool DeleteUser(User user)
{
UserService service = new UserService(); bool result = service.DeleteUsers(user.UserLogin);
return result; } public bool UpdateUser(User user)
{
UserService service = new UserService();
bool result = service.UpdateUsers(user);
return result;
}
}
}
注册界面代码regeister.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="register.aspx.cs" Inherits="register" %> <!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>
<br />
<asp:Label ID="Label1" runat="server" Text="姓名:"></asp:Label>
<asp:TextBox ID="nameText" runat="server"></asp:TextBox>
<br />
<br />
<asp:Label ID="Label2" runat="server" Text="帐号:"></asp:Label>
<asp:TextBox ID="loginText" runat="server"></asp:TextBox>
<br />
<br />
<asp:Label ID="Label3" runat="server" Text="密码:"></asp:Label>
<asp:TextBox ID="pwdText" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="注册" />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="转向登录" />
</div>
</form>
</body>
</html>
注册界面逻辑代码 regeister.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using testDAO.Library; public partial class register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ } public void CreateTable()
{
String connectionString = "server=.;Trusted_Connection=SSPI;database=easylife";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.ExecuteNonQuery();
connection.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
String userName = nameText.Text;
String userLogin = loginText.Text;
String userPwd = pwdText.Text; User user = new User();
user.UserName = userName;
user.UserLogin = userLogin;
user.UserPwd = userPwd; bool result = false;
UserManager manager = new UserManager();
result = manager.AddUser(user);
Response.Write(result);
if (result)
{
Response.Write("注册成功");
}
else
{
Response.Write("注册失败");
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("login.aspx");
}
}
regeister.aspx.cs
登录界面代码 login.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="login.aspx.cs" Inherits="login" %> <!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>
<br />
<asp:Label ID="Label1" runat="server" Text="帐号:"></asp:Label>
<asp:TextBox ID="loginText" runat="server"></asp:TextBox>
<br />
<br />
<asp:Label ID="Label2" runat="server" Text="密码:"></asp:Label>
<asp:TextBox ID="pwdText" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="loginButton" runat="server" onclick="loginButton_Click"
Text="登录" />
<asp:Button ID="Button1" runat="server" Text="转向注册" OnClick="Button1_Click" />
</div>
</form>
</body>
</html>
login.aspx
登录界面逻辑代码 login.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using testDAO.Library; public partial class login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("register.aspx");
} protected void loginButton_Click(object sender, EventArgs e)
{
User user = new User(); user.UserLogin = loginText.Text;
user.UserPwd = pwdText.Text; UserManager manager = new UserManager();
bool result = manager.Login(user);
if (result)
{
Response.Redirect("list.aspx");
}
else
{
Response.Write("登录失败,请输入正确的用户名和密码");
} }
}
login.aspx.cs
显示界面代码:
显示界面相关说明:
显示界面图片是这样:
当点击修改时图片如下:
点击修改时通过table获得table中的行数,从而改变行数中相应的内容,相关代码在javascript中
参数传值通过URL获取
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="list.aspx.cs" Inherits="list" %> <%@ Import Namespace="testDAO.Library" %>
<!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>
<table id="test" width="" align="center" border = "" cellpadding="" cellspacing="" bordercolordark="#808080" bordercolorlight="#ffffff" >
<tr>
<td align="center">序号</td>
<td align="center">姓名</td>
<td align="center">帐号</td>
<td align="center">密码</td>
<td align="center">修改</td>
<td align="center">删除</td>
</tr>
<%
UserManager manager = new UserManager();
List<User> list = manager.GetAllUsers(); for (int i = ; i < list.Count; i++)
{
Response.Write("<tr >");
Response.Write("<td align='center'>" + i + "</td>");
Response.Write("<td align='center'>" + list[i].UserName + "</td>");
Response.Write("<td align='center' id='loginText'>" + list[i].UserLogin + "</td>");
Response.Write("<td align='center'>" + list[i].UserPwd + "</td>"); Response.Write("<td align='center'><input type='Button' value='修改' onclick='test1("+i+")' >修改</td>");
Response.Write("<td align='center'><a href='userDelete.aspx?userLogin=" + list[i].UserLogin + "'>删除</a></td>"); Response.Write("</tr>");
}
%>
</table>
<asp:Button ID="button" runat="server" Text="转向注册" OnClick="Button1_Click" /> </div>
</form>
<script type="text/javascript"> function test1(j)
{
var table = document.getElementById("test");
table.rows[j + ].cells[].innerHTML = "<input type='text' id='nameText' >";
table.rows[j + ].cells[].innerHTML = "<input type='text' id='pwdText' >";
table.rows[j + ].cells[].innerHTML="<input type='button' value='确定' onclick='tiaozhuan("+j+")' >" }
function tiaozhuan(i) {
var table = document.getElementById("test");
var userName=document.getElementById("nameText").value;
var userPwd = document.getElementById("pwdText").value;
var userLogin=table.rows[i + ].cells[].innerHTML; location.href="userUpdate.aspx?userName="+ userName+"&userPwd="+userPwd+"&userLogin="+userLogin+" ";
}
</script>
</body>
</html>
list.aspx
list.aspx.cs代码只有通过点击button按钮转向到注册页面,对其它功能并无影响
通过点击修改进行更新逻辑代码 UserUpdate.aspx.cs代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using testDAO.Library; public partial class userUpdate : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ User user = new User(); user.UserName= Request.QueryString["userName"];
user.UserLogin = Request.QueryString["userLogin"];
user.UserPwd = Request.QueryString["userPwd"];
UserManager manager = new UserManager();
bool result = manager.UpdateUser(user);
if (result)
{
Response.Redirect("list.aspx");
}
else
{
Response.Write("修改失败");
} }
}
通过点击删除进行删除逻辑代码 userDelete.aspx.cs代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using testDAO.Library;
public partial class userDelete : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
User user = new User(); user.UserLogin = Request.QueryString["userLogin"]; UserManager manager = new UserManager();
bool result = manager.DeleteUser(user);
if (result)
{
Response.Redirect("list.aspx");
}
else
{
Response.Write("删除失败");
} }
}
ASP.net+SQL server2008简单的数据库增删改查 VS2012的更多相关文章
- SQL 的简单命令(增删改查)
数据库操作的资料: 链接: https://pan.baidu.com/s/1dFl3q6X 密码: nvy7-- 增:insert into 表名 (列名) values (值) ,'dew') - ...
- 通过Sql语句控制SQLite数据库增删改查
person类属性有Intenger id,String name,Intenger age,相应的构造方法和set get方法. package com.xh.tx.dao; import jav ...
- WindowsPhone8 数据库增删改查
今天第一次在博客园发表文章,如果有的地方写的不对,还请大家指出! 1.这就是一个简单wp8数据库增删改查 1.创建数据表Person [Table] public class Person : INo ...
- Asp.Net操作MySql数据库增删改查
Asp.Net操作MySql数据库增删改查,话不多说直接步入正题.git源码地址:https://git.oschina.net/gxiaopan/NetMySql.git 1.安装MySQL数据库 ...
- MyBatis学习(二)、SQL语句映射文件(2)增删改查、参数、缓存
二.SQL语句映射文件(2)增删改查.参数.缓存 2.2 select 一个select 元素非常简单.例如: <!-- 查询学生,根据id --> <select id=" ...
- Yii2.0高级框架数据库增删改查的一些操作(转)
yii2.0框架是PHP开发的一个比较高效率的框架,集合了作者的大量心血,下面通过用户为例给大家详解yii2.0高级框架数据库增删改查的一些操作 --------------------------- ...
- Yii2.0高级框架数据库增删改查的一些操作
yii2.0框架是PHP开发的一个比较高效率的框架,集合了作者的大量心血,下面通过用户为例给大家详解yii2.0高级框架数据库增删改查的一些操作 --------------------------- ...
- MyBatis学习 之 二、SQL语句映射文件(2)增删改查、参数、缓存
目录(?)[-] 二SQL语句映射文件2增删改查参数缓存 select insert updatedelete sql parameters 基本类型参数 Java实体类型参数 Map参数 多参数的实 ...
- Python实现mysql数据库增删改查
利用python操作mysql数据库用法简单,环境配置容易,本文将实现对库增.删.改.查的简易封装! 1. 环境配置 安装第三方包 ,导入模块 mysql.connector pip inst ...
随机推荐
- [HeadFirst-JSPServlet学习笔记][第二章:高层概述]
第二章:高层体系结构 容器 1 什么是容器? servelet没有main()方法.它们受控于另一个Java应用,这个Java应用称为容器(Container) Tomcat就是这样一个容器.Web服 ...
- [HeadFirst-HTMLCSS学习笔记][第三章创建网页]
一些基本元素 以下元素都可以用CSS变得更好看 q,<blockquote>,<em>,<br>, <strong>,ol ,ul,li,pre,cod ...
- HTTP协议5之代理--转
代理服务器 Web代理(proxy)服务器是网络的中间实体. 代理位于Web客户端和Web服务器之间,扮演“中间人”的角色. HTTP的代理服务器即是Web服务器又是Web客户端. Fiddler就是 ...
- js对象克隆, 深复制.
亲测有效: //对象克隆 function clone(obj) { // Handle the 3 simple types, and null or undefined if (null == o ...
- js简单排序
简单的排序功能 HTML代码: <body> <input id="btn1" type="button" value="排序&qu ...
- Dreamwaver 使用root用户连接不上远程服务器
我用dreamweaver连接远程服务,开始用的是root用户登录的,但是连接不上.网上查了一下,解决教程非常复杂,我就不列出来了. 后来我想了一下,之前我有连接过.我感觉可能是用户的问题,于是我在远 ...
- javascript 模仿回车键事件
<script> $(function(){ var _login = function (){ var _name = $('#name'); var _password = $('#p ...
- c# 配置连接 mysql
今天复习了下c#连接mysql 记录下来方便自己也方便别人! 使用vs2010连接mysql 数据库, 1.装连接驱动,使用Connector/Net 连接驱动!下载地址:http://dev.my ...
- shell之冒号的作用
冒号: :在shell中是一种命令,意思是总是为真,但是却不做任何操作,即总是为真的空命令 eg: [root@localhost ~]# ${abc:=t1}-bash: t1: comma ...
- CSS的伪类和伪元素
伪类 W3C:"W3C" 列指示出该属性在哪个 CSS 版本中定义(CSS1 还是 CSS2). 属性 描述 CSS :active 向被激活的元素添加样式. 1 :focus 向 ...