JDBC建立过程的4个步骤:
(1)建立数据库的一个连接;
(2)执行SQL语句;
(3)处理数据库返回结果;
(4)关闭数据库的连接。
JDBC的基本操作
建立一张人员信息表:
数据库操作
查询数据库:在查询数据库时候,记得关闭数据库,否则会占用连接,引发连接异常。
在Java中插入人员信息,主要用到executeUpdate(String sql)方法。该方法用于执行对数据库INSERT、UPDATE、DELETE操作,返回执行语句影响的行数,如果没有影响行数,就返回0。
package com.eshore;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.annotation.WebServlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
//给当前文件的路径设置为根目录下的GetReaderBody2
@WebServlet(
urlPatterns = { "/OperateServlet" },
name = "operateServlet"
)
public class OperateServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
String age = request.getParameter("age");
String sex = request.getParameter("sex");
String birthday = request.getParameter("birthday");
String description = request.getParameter("description");
String sql = "insert into person(name,age,sex,birthday,description) "+
"values('"+name+"','"+age+"','"+sex+"','"+birthday+"','"+description+"')";
Connection con = null;
Statement st = null;
int result = 0;
try {
Class.forName("com.mysql.cj.jdbc.Driver");//注册数据库
con = DriverManager.
getConnection("jdbc:mysql://localhost:3306/mydb","root","1234");//获取数据库连接
st = con.createStatement(); //获取Statement
result = st.executeUpdate(sql); //执行查询,返回结果集
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out .println("<!DOCTYPE HTML >");
out.println("<HTML>");
out.println(" <HEAD><TITLE>列出人员信息表</TITLE></HEAD>");
out.println(" <BODY>");
out.println("");
out.println("<a href=\""+request.getContextPath()+"/listPerson.jsp\">返回人员列表</a>");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {//关闭连接
st.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
%>
<!DOCTYPE HTML >
<html>
<head>
<title>增加人员列表</title>
<!-- 调用日期控件的js -->
<script language="javascript" type="text/javascript" src="${pageContext.request.contextPath}/My97DatePicker/WdatePicker.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.8.1.js"></script>
</head>
<body>
<form action="<%=path%>/OperateServlet" method="post">
<table>
<tr>
<td>姓名</td>
<td><input name="name"/></td>
</tr>
<tr>
<td>性别</td>
<td><select name="sex">
<option value="男">男</option>
<option value="女">女</option>
</select></td>
</tr>
<tr>
<td>年龄</td>
<td><input name="age"/></td>
</tr>
<tr>
<td>生日</td>
<!-- 调用日期控件 -->
<td><input id="d11" name="birthday" type="text" onClick="WdatePicker()"/></td>
</tr>
<tr>
<td>描述</td>
<td><textarea name="description"></textarea></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="提交"/>
</td>
</tr>
</table>
</form>
</body>
</html>
删除人员信息:
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE HTML >
<HTML>
<HEAD>
<TITLE>删除人员信息</TITLE>
</HEAD>
<BODY>
<%
Connection con = null;
Statement st = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver"); //注册数据库
con = DriverManager.getConnection( //获取数据库连接
"jdbc:mysql://localhost:3306/mydb","root","1234");
st = con.createStatement(); //获取Statement
request.setCharacterEncoding("UTF-8");
String id = request.getParameter("id"); //获取页面参数id
String sql = "delete from Person where id='"+id+"'"; //删除指定人员
int result = st.executeUpdate(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//记住关闭连接
try {
st.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
%>
<a href="listPerson.jsp">返回人员信息列表</a>
<br/>
</BODY>
</HTML>
修改人员信息:
package com.eshore;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.annotation.WebServlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
//给当前文件的路径设置为根目录下的GetReaderBody2
@WebServlet(
urlPatterns = { "/OperateServlet" },
name = "operateServlet"
)
public class OperateServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
String age = request.getParameter("age");
String sex = request.getParameter("sex");
String birthday = request.getParameter("birthday");
String description = request.getParameter("description");
String sql = "insert into person(name,age,sex,birthday,description) "+
"values('"+name+"','"+age+"','"+sex+"','"+birthday+"','"+description+"')";
Connection con = null;
Statement st = null;
int result = 0;
try {
Class.forName("com.mysql.cj.jdbc.Driver");//注册数据库
con = DriverManager.
getConnection("jdbc:mysql://localhost:3306/mydb","root","1234");//获取数据库连接
st = con.createStatement(); //获取Statement
result = st.executeUpdate(sql); //执行查询,返回结果集
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out .println("<!DOCTYPE HTML >");
out.println("<HTML>");
out.println(" <HEAD><TITLE>列出人员信息表</TITLE></HEAD>");
out.println(" <BODY>");
out.println("");
out.println("<a href=\""+request.getContextPath()+"/listPerson.jsp\">返回人员列表</a>");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {//关闭连接
st.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE HTML >
<HTML>
<HEAD>
<TITLE>修改人员信息</TITLE>
</HEAD>
<BODY>
<%
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver"); //注册数据库
con = DriverManager.getConnection( //获取数据库连接
"jdbc:mysql://localhost:3306/mydb","root","1234");
st = con.createStatement(); //获取Statement
request.setCharacterEncoding("UTF-8");
//获得修改人员的主键ID
String id = request.getParameter("id");
//查询该人员的SQL语句
String sql = "select * from Person where id='"+id+"'";
rs = st.executeQuery(sql);
if(rs.next()){
//往页面传递人员信息参数
request.setAttribute("id",rs.getInt("id"));
request.setAttribute("name",rs.getString("name"));
request.setAttribute("sex",rs.getString("sex"));
request.setAttribute("age",rs.getInt("age"));
request.setAttribute("birthday",rs.getString("birthday"));
request.setAttribute("description",rs.getString("description"));
RequestDispatcher rd = request.getRequestDispatcher("update.jsp");
rd.forward(request,response);
}else{
out.println("没有找到id为"+id+"的人员记录");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {//记住关闭数据库连接
rs.close();
st.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
%>
<br/>
</BODY>
</HTML>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML >
<html>
<head>
<title>修改人员</title>
<!-- 调用日期控件的js -->
<script language="javascript" type="text/javascript" src="${pageContext.request.contextPath}/My97DatePicker/WdatePicker.js"></script>
</head>
<%
//获取传递的参数信息
Integer id = (Integer)request.getAttribute("id");
String name = (String)request.getAttribute("name");
Integer age = (Integer)request.getAttribute("age");
String sex = (String)request.getAttribute("sex");
String birthday = (String)request.getAttribute("birthday");
String description = (String)request.getAttribute("description");
%>
<body>
<form action="${pageContext.request.contextPath}/ModifyServlet?id=<%=id%>" method="post">
<table>
<tr>
<td>姓名</td>
<td><input name="name" value="<%=name %>" />
</td>
</tr>
<tr>
<td>性别</td>
<td><select name="sex">
<%
if("男".equals(sex)){
%>
<option value="男" selected>男</option>
<%
}else{
%>
<option value="男" >男</option>
<%
}
%>
<%
if("女".equals(sex)){
%>
<option value="女" selected>女</option>
<%
}else{
%>
<option value="女" >女</option>
<%
}
%>
</select></td>
</tr>
<tr>
<td>年龄</td>
<td><input name="age" value="<%=age%>"/></td>
</tr>
<tr>
<td>生日</td>
<!-- 调用日期控件 -->
<td><input id="d11" name="birthday" type="text" onClick="WdatePicker()" value="<%=birthday %>"/></td>
</tr>
<tr>
<td>描述</td>
<td><textarea name="description" ><%=description %></textarea></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="提交"/>
</td>
</tr>
</table>
</form>
</body>
</html>
使用PreparedStatement:
package com.eshore;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
@WebServlet(
urlPatterns = { "/ModifyServletPrepared" },
name = "modifyServletPrepared"
)
public class ModifyServletPrepared extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String id = request.getParameter("id");
String name = request.getParameter("name");
String age = request.getParameter("age");
String sex = request.getParameter("sex");
String birthday = request.getParameter("birthday");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String description = request.getParameter("description");
String sql = "update Person set name=?,age=?,sex=?,birthday=?,description=? where id=?";
Connection con = null;
PreparedStatement prest = null;
int result = 0;
try {
Class.forName("com.mysql.cj.jdbc.Driver"); //注册数据库
con = DriverManager.getConnection( //获取数据库连接
"jdbc:mysql://localhost:3306/mydb","root","1234");
prest = con.prepareStatement(sql); //获取PreparedStatement,并且预编译SQL语句
prest.setString(1, name);
prest.setInt(2, Integer.parseInt(age)); //设定第2个参数
prest.setString(3, sex); //设定第3个参数
Date date = new Date(sdf.parse(birthday).getTime());
prest.setDate(4, date); //设定第4个参数
prest.setString(5, description); //设定第5个参数
prest.setInt(6, Integer.parseInt(id)); //设定第6个参数
result = prest.executeUpdate(sql); //执行查询,返回结果集
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out .println("<!DOCTYPE HTML >");
//���ҳ������
out.println("<HTML>");
out.println(" <HEAD><TITLE>列出人员信息表</TITLE></HEAD>");
out.println(" <BODY>");
out.println("");
out.println("<a href=\""+request.getContextPath()+"/listPerson.jsp\">返回人员列表</a>");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {//记住关闭连接
prest.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
利用Statement与PreparedStatement批处理SQL:
package com.eshore;
import java.sql.*;
public class PreparedStatementBatch {
public static void main(String[] args){
String sql = "insert into Person(name,age,sex,birthday,description) values(?,?,?,?,?)";
Connection con = null;
PreparedStatement prest = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");//注册数据库
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","1234");//获取数据库连接
prest = con.prepareStatement(sql); //获取PreparedStatement,并且预编译SQL语句
for(int i=0;i<=10;i++){
prest.setString(1, "李四"+i); //设定第1个参数
prest.setInt(2, 30); //设定第2个参数
prest.setString(3, "男"); //设定第3个参数
prest.setDate(4, //设定第4个参数
new Date(System.currentTimeMillis()));
prest.setString(5, "PreparedStatement 批量插入"); //设定第5个参数
prest.addBatch(); //添加SQL语句
}
int[] result = prest.executeBatch(); //执行批量插入,返回结果集
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//记住关闭连接
try {
prest.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
带条件的查询:
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE HTML >
<HTML>
<HEAD>
<TITLE>查询人员信息列表</TITLE>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.8.1.js"></script>
<!-- 调用日期控件的js -->
<script language="javascript" type="text/javascript" src="${pageContext.request.contextPath}/My97DatePicker/WdatePicker.js"></script>
</HEAD>
<BODY>
<%--<user>
<name>张三</name>
<english-name>zhangsan</english-name>
<age>20</age>
<sex>男</sex>
<address>广东省广州市</address>
<description>他是一个工程师</description>
</user>--%>
<user>
<property name="name" value="张三"/>
<property name="english-name" value="zhangsan"/>
<property name="age" value="20"/>
<property name="sex" value="男"/>
<property name="address" value="广东省广州市"/>
<property name="description" value="他是一个工程师"/>
</user>
<h4 style="text-align: center;">人员信息列表</h4>
<%
//获取页面查询条件
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
String sex = request.getParameter("sex");
String age = request.getParameter("age");
String description = request.getParameter("description");
String startTime = request.getParameter("startTime");
String endTime = request.getParameter("endTime");
Connection con = null;
PreparedStatement st = null;
ResultSet rs = null;
//组合SQL的where条件
String sql = "select * from person where 1=1 ";
if(name!=null&&!"".equals(name)){
sql+="and name like '%"+name+"%'";
}
if(sex!=null&&!"".equals(sex)){
sql+="and sex ='"+sex+"'";
}
if(age!=null&&!"".equals(age)){
sql+="and age ='%"+age+"'";
}
if(description!=null&&!"".equals(description)){
sql+="and description like '%"+description+"%'";
}
if(startTime!=null&&!"".equals(startTime)){
sql+="and birthday >= '"+startTime+"'";
}
if(endTime!=null&&!"".equals(endTime)){
sql+="and birthday <= '%"+endTime+"'";
}
try {
Class.forName("com.mysql.cj.jdbc.Driver"); //注册数据库
con = DriverManager.getConnection( //获取数据库连接
"jdbc:mysql://localhost:3306/mydb","root","1234");
st = con.prepareStatement(sql); //获取Statement
rs = st.executeQuery(sql); //执行查询,返回结果集
%>
<form action="searchPerson.jsp" method="post">
<table>
<tr>
<td>姓名:</td>
<td><input name="name"/></td>
<td>性别:</td>
<td><select name="sex" style="width:100">
<option value="">无限制</option>
<option value="男">男</option>
<option value="女">女</option>
</select></td>
</tr>
<tr>
<td>年龄:</td>
<td><input name="age"/></td>
<td>备注:</td>
<td><input name="description"/></td>
</tr>
<td colspan="4">出生日期:
<label> 从:</label><input class="Wdate" name="startTime" id="startBeginTime" onFocus="WdatePicker({dateFmt:'yyyyMMdd HH:mm:ss',minDate:'1900-01-01'})"/>
到
<input class="Wdate" name="endTime" id="endBeginTime" onFocus="WdatePicker({dateFmt:'yyyyMMdd HH:mm:ss',minDate:'1900-01-01'})"/></td>
</tr>
<tr>
<td>
<input type="submit" value="提交">
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
<br/>
<br/>
<table border="1" width="100%" cellpadding="2" cellspacing="1">
<tr>
<td>选择</td>
<td>姓名</td>
<td>年龄</td>
<td>性别</td>
<td>生日</td>
<td>备注</td>
<td>操作</td>
</tr>
<%
//遍历结果集ResultSet
while(rs.next()){
int id = rs.getInt("id"); //获取ID
String name2 = rs.getString("name"); //获取姓名
int age2 = rs.getInt("age"); //获取年龄
String sex2 = rs.getString("sex"); //获取性别
Date birthday = rs.getDate("birthday"); //获取出生日期
String description2 = rs.getString("description"); //获取备注
out.println("<tr>");
out.println("<td><input type=\"checkbox\" name=\"checkPerson\" value=\""+id+"\"></td>");
out.println("<td >"+name2+"</td>");
out.println("<td >"+age2+"</td>");
out.println("<td >"+sex2+"</td>");
out.println("<td >"+birthday+"</td>");
out.println("<td >"+description2+"</td>");
out.println("<td><a href=\"modify.jsp?id="+id+"\">修改</a> "+
"<a href=\"delete.jsp?id="+id+"\" οnclick=\"return confirm('确定删除该记录?')\">删除</a></td>");
out.println("</tr>");
}
%>
</table>
<table>
<tr>
<td>
全选<input type="checkbox" onclick="selectPerson(this);"/>
</td>
</tr>
</table>
<%
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//记住关闭连接
try {
rs.close();
st.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
%>
</BODY>
<script type="text/javascript">
function selectPerson(obj){
$('input[name="checkPerson"]').attr("checked",obj.checked);
}
</script>
</HTML>
通过ResultSetMetaData可以获得元数据内容,通过它可以直接得知列名,可以动态的显示查询各列内容:
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE HTML >
<HTML>
<HEAD>
<TITLE>人员信息列表</TITLE>
</HEAD>
<BODY>
<div style="text-align: center;">
<h4>人员信息列表</h4>
</div>
<%
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver"); //注册数据库
con = DriverManager.getConnection( //获取数据库连接
"jdbc:mysql://localhost:3306/mydb","root","1234");
st = con.createStatement(); //获取Statement
rs = st.executeQuery("select * from person");//执行查询,返回结果集;
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount= rsmd.getColumnCount(); //获取列数
String[] columnNames = new String[columnCount];
for(int i=0;i<columnCount;i++){ //获取列对应的列名
columnNames[i] = rsmd.getColumnName(i+1);
}
out.println("<table border=\"1\" width=\"100%\" cellpadding=\"2\" cellspacing=\"1\"><tr>");
for(int i=0;i<columnCount;i++){ //输出列名
out.println("<td>"+columnNames[i]+"</td>");
}
out.println("</tr>");
//遍历结果集ResultSet
while(rs.next()){
out.println("</tr>");
//根据列名取得对应列的值
for(int i=0;i<columnCount;i++){
out.println("<td>"+rs.getString(columnNames[i])+"</td>");
}
out.println("</tr>");
}
out.println("</table>");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//记住关闭连接
try {
rs.close();
st.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
%>
</BODY>
</HTML>