该项目的结构如下图所示:
打开MySQL,输入默认超级root用户的密码,然后数据库的操作如下代码:
--创建数据库
create database TestDao;
--使用数据库
use TestDao;
--创建学生表
create table student(
stuid int,
username varchar(20),
password varchar(20)
);
--插入数据
insert student(stuid,username,password)
values ("10001","Eastmount","111111");
insert student(stuid,username,password)
values ("10002","Yangxiuzhang","123456");
--显示表结构
desc student;
--查询表中数据
select * from student;
其中表结构和表中数据显示如下图:
1.在src下新建文件夹util,然后添加类JDBCConnect.java。代码如下:
package util;
import java.sql.*;
import com.mysql.jdbc.Driver;
public class JDBCConnect {
//获取默认数据库连接
public static Connection getConnection() throws SQLException {
return getConnection("TestDAO", "root", "123456"); //数据库名 默认用户 密码
}
//连接数据库 参数:数据库名 root登录名 密码
public static Connection getConnection(String dbName, String userName,
String password) throws SQLException {
String url = "jdbc:mysql://localhost:3306/" + dbName
+ "?characterEncoding=utf-8";
//连接MySQL"com.mysql.jdbc.Driver"
DriverManager.registerDriver(new Driver());
return DriverManager.getConnection(url, userName, password);
}
//设置 PreparedStatement 参数
public static void setParams(PreparedStatement preStmt, Object... params)
throws SQLException {
if (params == null || params.length == 0)
return;
for (int i = 1; i <= params.length; i++) {
Object param = params[i - 1];
if (param == null) {
preStmt.setNull(i, Types.NULL);
} else if (param instanceof Integer) {
preStmt.setInt(i, (Integer) param);
} else if (param instanceof String) {
preStmt.setString(i, (String) param);
} else if (param instanceof Double) {
preStmt.setDouble(i, (Double) param);
} else if (param instanceof Long) {
preStmt.setDouble(i, (Long) param);
} else if (param instanceof Timestamp) {
preStmt.setTimestamp(i, (Timestamp) param);
} else if (param instanceof Boolean) {
preStmt.setBoolean(i, (Boolean) param);
} else if (param instanceof Date) {
preStmt.setDate(i, (Date) param);
}
}
}
//执行 SQL,返回影响的行数 异常处理
public static int executeUpdate(String sql) throws SQLException {
return executeUpdate(sql, new Object[] {});
}
//带参数执行SQL,返回影响的行数 异常处理
public static int executeUpdate(String sql, Object... params)
throws SQLException {
Connection conn = null;
PreparedStatement preStmt = null;
try {
conn = getConnection();
preStmt = conn.prepareStatement(sql);
setParams(preStmt, params);
return preStmt.executeUpdate(); //执行SQL操作
} finally {
if (preStmt != null)
preStmt.close();
if (conn != null)
conn.close();
}
}
}
其中主要是调用getConnection(url, userName, password); 方法进行连接数据库操作,我数据库的名称为TestDAO,默认的连接对象为root,密码为123456。同时定义两个函数执行无参数的SQL语句操作和有参数的SQL语句操作。
2.在src下新建文件夹bean,然后添加类Student.java。代码如下:
package bean;
public class Student {
private Integer id; //学号
private String name; //姓名
private String password; //密码
public Integer getId() { return id; }
public String getName() { return name; }
public String getPassword() { return password; }
public void setId(Integer id) { this.id = id; }
public void setName(String name) { this.name = name; }
public void setPassword(String pwd) { this.password = pwd; }
}
该Student中的变量及类型与数据库中一一对应,在通过get和set方法获取和设置其值。同样如果你的数据库中有老师、学校表,你只需要在bean文件夹下添加Teacher.java和School.java即可。
3.在src下新建文件夹DAO,然后添加类StudentDAO.java。代码如下:
package DAO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import bean.Student;
import util.JDBCConnect;
public class StudentDAO {
//插入学生
public static int insert(Student stu) throws Exception {
String sql = "INSERT INTO student (stuid,username,password) VALUES (?,?,?) ";
return JDBCConnect.executeUpdate(sql, stu.getId(),stu.getName(),stu.getPassword());
}
//更新学生姓名
public static int update(Student stu) throws Exception {
String sql = "UPDATE student SET stuid = ? WHERE username = ? ";
return JDBCConnect.executeUpdate(sql,stu.getId(),stu.getName());
}
//删除操作
public static int delete(Integer id) throws Exception {
String sql = "DELETE FROM student WHERE stuid = ? ";
return JDBCConnect.executeUpdate(sql, id);
}
//查找记录 某学号
public static Student find(Integer id) throws Exception {
String sql = "SELECT * FROM student WHERE stuid = ? ";
Connection conn = null;
PreparedStatement preStmt = null;
ResultSet rs = null;
try {
//链接数据库执行SQL语句
conn = JDBCConnect.getConnection(); //连接默认数据库
preStmt = conn.prepareStatement(sql);
preStmt.setInt(1, id);
rs = preStmt.executeQuery();
//获取查询结果
if (rs.next()) {
Student student = new Student();
student.setId(rs.getInt("stuid"));
student.setName(rs.getString("username"));
return student;
} else {
return null;
}
} finally { //依次关闭 记录集 声明 连接对象
if (rs != null)
rs.close();
if (preStmt != null)
preStmt.close();
if (conn != null)
conn.close();
}
}
//查询所有学生信息
public static List listStudents() throws Exception {
List list = new ArrayList();
String sql = "SELECT * FROM student";
Connection conn = null;
PreparedStatement preStmt = null;
ResultSet rs = null;
try {
conn = JDBCConnect.getConnection();
preStmt = conn.prepareStatement(sql);
rs = preStmt.executeQuery();
while (rs.next()) {
//设置数据库中表参数 否则报错java.sql.SQLException: Column 'id' not found.
Student student = new Student();
student.setId(rs.getInt("stuid"));
student.setName(rs.getString("username"));
student.setPassword(rs.getString("password"));
list.add(student);
}
} finally {
if (rs != null)
rs.close();
if (preStmt != null)
preStmt.close();
if (conn != null)
conn.close();
}
return list;
}
}
通常DAO(Data Access Object)数据访问对象是负责与数据库连接,主要功能执行对数据表的CUDR操作。然后是WebRoot文件夹下的jsp代码。其中index.jsp如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
My JSP 'index.jsp' starting page
This is my JSP page.
JDBC操作
然后点击JDBC操作跳转到student.jsp操作,代码如下:涉及EL和JSTL。
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
List studentList = StudentDAO.listStudents();
request.setAttribute("studentList", studentList);
%>
My JSP 'student.jsp' starting page
文章运行结果如下图所示:
最后总结下,文章主要讲述了如何通过DAO和Java Bean实现Java数据库操作、界面显示分离的操作;同样的道理,实现修改、删除、插入方法类似,后面可能会讲述。该方法主要是通过上一篇自己的体会,找到的解决办法。最后希望文章对你有所帮助,如果有错误或不足之处,还请海涵~
最重要的一个问题,在这过程中你可能会遇到以下两个错误:(困扰我4小时)
Servlet.service() for servlet [jsp] in context with path
javax.el.PropertyNotFoundException: Property 'id' not found on type bean.Student
其解决方案参考:http://blog.csdn.net/eastmount/article/details/45835481
(By:Eastmount 2015-5-19 凌晨2点 http://blog.csdn.net/eastmount/)