一、JDBC连接SQLserver数据库的步骤:
1.下载SQLserver的JDBC驱动文件——Microsoft JDBC Driver 4.0 for SQL Server
2.例如下载得到的文件是sqljdbc_4.0.2206.100_chs.exe,解压文件,将解压缩文件中的sqljdbc4.jar放到eclipse-workspace\User_Message(新建的JavaWeb项目)\WebContent\WEB-INF\lib目录下
3.加载JDBC驱动程序:在连接数据库之前,首先要加载想要连接的数据库的驱动到JVM(Java虚拟机),这通过java.lang.Class类的静态方法forName(String className)实现,成功加载后,会将Driver类的实例注册到DriverManager类中
示例语句:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
4.创建连接对象:要连接数据库,需要向java.sql.DriverManager请求并获得Connection对象, 该对象就代表一个数据库的连接,使用DriverManager的getConnectin(String url , String username , String password )方法传入指定的欲连接的数据库的路径、数据库的用户名和密码,其中url定义了连接数据库时的协议、子协议、数据源标识,协议——在JDBC中总是以jdbc开始,子协议——是桥连接的驱动程序或是数据库管理系统名称,数据源标识——标记找到数据库来源的地址与连接端口。
示例语句:
String user="sa"; String password="woshizcy0919"; String url= "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=User_DB"; Connection connection=DriverManager.getConnection(url, user, password);
5.准备SQL语句:
示例语句:
String sql="select count(*) from t_user where username=?";
6.执行SQL语句:先将SQL语句赋给preparedStatement对象,下面有两种执行SQL语句的方法executeQuery 、executeUpdate
(1)ResultSet executeQuery():执行查询数据库的SQL语句,返回值为一个结果集(ResultSet)对象。
(2)int executeUpdate():执行INSERT、UPDATE或DELETE语句以及SQL DDL语句(如:CREATE TABLE和DROP TABLE等),并更新数据库,返回值为本次操作影响的行数,即记录数。
示例语句:
PreparedStatement preparedStatement=
connection.prepareStatement(sql);
preparedStatement.setString(1, user.getUsername());
resultSet=preparedStatement.executeQuery();
preparedStatement.executeUpdate();
7.操作结果集对象:
结果集中包含符合SQL语句查询条件的所有行,即所有记录,并且它通过一套get方法提供了对这些行中数据的访问,使用结果集对象(resultSet)的访问方法获取数据。
(1)resultSet.next():读取结果集中的下一行,即下一条记录。
(2)resultSet.getInt(int index)
resultSet.getInt(String columName):
通过索引或者列名来获得查询结果集中的某一列的值。
示例语句:
//例:现有表User:列有id,name String sql="select * from User"; ResultSet resultSet = null; resultSet = preparedStatement.executeQuery(sql); while(resultSet.next) { resultSet.getInt(1)//等价于resultSet.getInt("id"); resultSet.getString(2)//等价于resultSet.getInt("name"); }
8.关闭JDBC对象:
示例语句:
DBUtil.close(resultSet);
DBUtil.close(preparedStatement);
DBUtil.close(connection);
二、登录界面及其功能设计
1.对数据库操作方法的接口
package com.jaovo.msg.dao; import java.util.List; import com.jaovo.msg.model.User; public interface IUserDao { public void add(User user); public void delete(int id); public void update(User user); public User load(int id); public User load(String username); public Listload(); }
2.实现接口的类
package com.jaovo.msg.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import com.jaovo.msg.Util.DBUtil; import com.jaovo.msg.Util.UserException; import com.jaovo.msg.model.User; public class UserDaoImpl implements IUserDao { public void add(User user) { //获得连接的对象 Connection connection=DBUtil.getConnection(); //准备sql语句 String sql="select count(*) from t_user where username=?"; //创建语句传输对象 PreparedStatement preparedStatement=null; ResultSet resultSet=null; try { preparedStatement=connection.prepareStatement(sql); preparedStatement.setString(1, user.getUsername()); //接收结果集 resultSet=preparedStatement.executeQuery(); //遍历结果集 while(resultSet.next()) { if(resultSet.getInt(1)>0) { throw new UserException("用户已存在!"); } } sql="insert into t_user(username,nickname,password) values(?,?,?)"; preparedStatement=connection.prepareStatement(sql); preparedStatement.setString(1, user.getUsername()); preparedStatement.setString(2, user.getNickname()); preparedStatement.setString(3, user.getPassword()); preparedStatement.executeUpdate(); //重写底层代码: /* sql="insert into t_user(id,username,userpassword,nickname)values('"+user.getId()+"','"+user.getUsername()+"','"+user.getPassword()+"','"+user.getNickname()+"')"; Statement stmt; Connection con=DBUtil.getConnection(); stmt=con.createStatement(); stmt.executeUpdate(sql); */ //重写结束 } catch (SQLException e) { e.printStackTrace(); } finally { //关闭JDBC对象 DBUtil.close(resultSet); DBUtil.close(preparedStatement); DBUtil.close(connection); } } public void delete(int id) { //获得连接的对象 Connection connection=DBUtil.getConnection(); //准备sql语句 String sql="delete from t_user where id=?"; //创建语句传输对象 PreparedStatement preparedStatement=null; try { preparedStatement=connection.prepareStatement(sql); preparedStatement.setInt(1, id); preparedStatement.executeUpdate(); } catch(SQLException e) { e.printStackTrace(); } finally { DBUtil.close(preparedStatement); DBUtil.close(connection); } } public void update(User user) { //获得连接的对象 Connection connection=DBUtil.getConnection(); //准备sql语句 String sql="delete from t_user where id=?"; //创建语句传输对象 PreparedStatement preparedStatement=null; try { preparedStatement=connection.prepareStatement(sql); preparedStatement.setString(1, user.getUsername()); preparedStatement.setString(2, user.getNickname()); preparedStatement.setInt(3, user.getId()); preparedStatement.executeUpdate(); } catch(SQLException e) { e.printStackTrace(); } finally { DBUtil.close(preparedStatement); DBUtil.close(connection); } } public User load(int id) { //获得连接的对象 Connection connection=DBUtil.getConnection(); //准备sql语句 String sql="select * from t_user where id=?"; //创建语句传输对象 PreparedStatement preparedStatement=null; ResultSet resultSet=null; User user=null; try { preparedStatement=connection.prepareStatement(sql); preparedStatement.setInt(1, id); resultSet=preparedStatement.executeQuery(); while(resultSet.next()) { user=new User(); user.setId(id); user.setUsername(resultSet.getString("username")); user.setPassword(resultSet.getString("password")); user.setNickname(resultSet.getString("nickname")); } } catch(SQLException e) { e.printStackTrace(); } finally { DBUtil.close(resultSet); DBUtil.close(preparedStatement); DBUtil.close(connection); } return user; } public User load(String username) { //获得连接的对象 Connection connection=DBUtil.getConnection(); //准备sql语句 String sql="select * from t_user where username=?"; //创建语句传输对象 PreparedStatement preparedStatement=null; ResultSet resultSet=null; User user=null; try { preparedStatement=connection.prepareStatement(sql); preparedStatement.setString(1, username); resultSet=preparedStatement.executeQuery(); while(resultSet.next()) { user=new User(); user.setId(resultSet.getInt("id")); user.setUsername(username); user.setPassword(resultSet.getString("password")); user.setNickname(resultSet.getString("nickname")); } } catch(SQLException e) { e.printStackTrace(); } finally { DBUtil.close(resultSet); DBUtil.close(preparedStatement); DBUtil.close(connection); } return user; } public Listload() { //获得连接的对象 Connection connection=DBUtil.getConnection(); //准备sql语句 String sql="delete from t_user where id=?"; //创建语句传输对象 PreparedStatement preparedStatement=null; ResultSet resultSet=null; List users=new ArrayList (); User user=null; try { preparedStatement=connection.prepareStatement(sql); resultSet=preparedStatement.executeQuery(); while(resultSet.next()) { user=new User(); user.setId(resultSet.getInt("id")); user.setUsername(resultSet.getString("username")); user.setNickname(resultSet.getString("nickname")); user.setPassword(resultSet.getString("password")); users.add(user); } } catch(SQLException e) { e.printStackTrace(); } finally { DBUtil.close(resultSet); DBUtil.close(preparedStatement); DBUtil.close(connection); } return users; } //检查密码是不是错误 public boolean check(User user) { boolean flag=false; Connection connection=DBUtil.getConnection(); String sql="select * from t_user where username=?"; PreparedStatement preparedStatement = null; ResultSet resultSet=null; try { preparedStatement=connection.prepareStatement(sql); preparedStatement.setString(1,user.getUsername()); resultSet=preparedStatement.executeQuery(); while(resultSet.next()) { if(resultSet.getString("password").equals(user.getPassword().toString().trim())) { flag=true; break; } } } catch (SQLException e) { e.printStackTrace(); } return flag; } }
3.用户模型类
package com.jaovo.msg.model; public class User { private int id; private String username; private String nickname; private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
4.工具类(用于连接数据库和关闭JDBC对象)
package com.jaovo.msg.Util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class DBUtil { public static Connection getConnection() { try { //加载驱动 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); System.out.println("驱动加载成功!"); } catch(ClassNotFoundException | InstantiationException | IllegalAccessException e) { System.out.println("驱动加载失败!"); e.printStackTrace(); } String user="sa"; String password="woshizcy0919"; String url="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=User_DB"; Connection connection=null; try { //创建链接对象connection connection=DriverManager.getConnection(url, user, password); System.out.println("数据库连接成功!"); } catch(SQLException e) { System.out.println("数据库连接失败!"); e.printStackTrace(); } return connection; } //关闭资源的方法 public static void close(Connection connection) { if(connection!=null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void close(PreparedStatement preparedStatement) { if(preparedStatement !=null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void close(ResultSet resultSet) { if(resultSet!=null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
5.异常抛出类
package com.jaovo.msg.Util; public class UserException extends RuntimeException { public UserException() { super(); } public UserException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public UserException(String message, Throwable cause) { super(message, cause); } public UserException(String message) { super(message); } public UserException(Throwable cause) { super(cause); } }
6.jsp界面代码
(1)登录界面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>欢迎来到登录界面title> head> <body> <%=request.getAttribute("error") %> <form action="LoginCheck.jsp" method="post"> <table align="center" border="1" width="500"> <caption>用户登录caption> <tr> <td>账号:td> <td> <input type="text" name="username"/> td> tr> <tr> <td>密码:td> <td> <input type="password" name="password"> td> tr> <tr align="center"> <td colspan="2"> <input type="submit" value="登录"/> <input type="button" value="注册" onClick="window.location.href='addInput.jsp'"/> td> tr> table> form> body> html>
(2)登录验证界面
<%@page import="com.jaovo.msg.Util.UserException"%> <%@page import="com.jaovo.msg.dao.UserDaoImpl"%> <%@page import="com.jaovo.msg.model.User"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>用户身份验证title> head> <body> <% //接收客户端传递过来的参数 String username = request.getParameter("username"); String password = request.getParameter("password"); if(username == null || "".equals(username.trim())||password == null || "".equals(password.trim())) { request.setAttribute("error", "用户名和密码不能为空!"); %> <jsp:forward page="Login.jsp">jsp:forward> <% } %> <% User user = new User(); user.setUsername(username); user.setPassword(password); UserDaoImpl userDao = new UserDaoImpl(); try { if(userDao.load(username)==null) { throw new UserException(); } if(userDao.check(user)==true) { %> 登录成功!<br> <% } else { %> 密码输入错误!<br> <% } } catch(UserException e) { %> <h2 style="color:red ; font-size:50px">该用户名不存在h2> <% } %> body> html>
(3)用户注册界面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>用户添加页面title> head> <body> <form action="add.jsp" method="get"> <table align="center" border="1" width="500"> <tr> <td>用户名称 : td> <td> <input type="text" name="username" /> td> tr> <tr> <td>用户密码:td> <td> <input type="password" name="password" /> td> tr> <tr> <td>用户昵称:td> <td> <input type="text" name="nickname" /> td> tr> <%=request.getAttribute("error") %> <tr align="center"> <td colspan="2"> <input type="submit" value="提交" /> <input type="reset" value="重置" /> td> tr> table> form> body> html>
(4)注册结果界面
<%@page import="com.jaovo.msg.Util.UserException"%> <%@page import="com.jaovo.msg.dao.UserDaoImpl"%> <%@page import="com.jaovo.msg.model.User"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>用户添加页面title> head> <body> <% //接收客户端传递过来的参数 String username = request.getParameter("username"); String password = request.getParameter("password"); String nickname = request.getParameter("nickname"); if(username == null || "".equals(username.trim())||password == null || "".equals(password.trim())){ request.setAttribute("error", "用户名和密码不能为空!"); %> <jsp:forward page="addInput.jsp">jsp:forward> <% } %> <% User user = new User(); user.setUsername(username); user.setPassword(password); user.setNickname(nickname); UserDaoImpl userDao = new UserDaoImpl(); try{ userDao.add(user); %> 注册成功!<br> <a href="addInput.jsp">返回a><br> <a href="#">用户列表a> <% }catch(UserException e){ %> <h2 style="color:red ; font-size:50px">发生错误 : <%=e.getMessage() %>h2> <% } %> body> html>
7.运行结果界面截图:
(1)登录界面
(2)登录成功
(3)用户名或密码为空
(4)用户名不存在
(5)密码错误
(6)注册界面
(7)注册成功
(8)注册重复