import
java
.
sql
.
Connection
;
import
java
.
sql
.
DriverManager
;
import
java
.
sql
.
PreparedStatement
;
import
java
.
sql
.
SQLException
;
import
java
.
sql
.
Statement
;
* 利用PreparedStatement进行增删改数据
* @author 2Π
public
class
Demo03
{
public
static
void
main
(
String
[
]
args
)
{
Connection conn
=
null
;
PreparedStatement ps
=
null
;
try
{
Class
.
forName
(
"com.mysql.jdbc.Driver"
)
;
conn
=
(
Connection
)
DriverManager
.
getConnection
(
"jdbc:mysql://localhost:3306/testjdbc"
,
"root"
,
"000000"
)
;
String addStr
=
"insert into tb_user (uName,uPwd,reTime) values (?,?,?)"
;
ps
=
conn
.
prepareStatement
(
addStr
)
;
ps
.
setObject
(
1
,
"张三"
)
;
ps
.
setObject
(
2
,
"000000"
)
;
ps
.
setObject
(
3
,
new
java
.
sql
.
Date
(
System
.
currentTimeMillis
(
)
)
)
;
if
(
ps
.
executeUpdate
(
)
>
0
)
{
System
.
out
.
println
(
"插入成功!"
)
;
}
catch
(
ClassNotFoundException
e
)
{
e
.
printStackTrace
(
)
;
}
catch
(
SQLException
e
)
{
e
.
printStackTrace
(
)
;
}
finally
{
if
(
ps
!=
null
)
{
try
{
ps
.
close
(
)
;
}
catch
(
SQLException
e
)
{
e
.
printStackTrace
(
)
;
if
(
conn
!=
null
)
{
try
{
ps
.
close
(
)
;
}
catch
(
SQLException
e
)
{
e
.
printStackTrace
(
)
;
这里举的是插入即添加数据的例子,更新与删除只要改下sql语句就行。
比如将刚刚插入的数据读出来。
package com.yzx.JDBC01;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
* 查询数据库中的结果并打印至控制台
* @author 2Π
public class Demo04 {
public static void main(String[] args){
Connection conn =null;
PreparedStatement ps =null;
ResultSet rs =null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","000000");
String sqlStr = "select * from tb_user where uName=?";
ps = conn.prepareStatement(sqlStr);
ps.setString(1, "张三");
rs = ps.executeQuery();
System.out.println("id\t姓名\t密码\t");
while (rs.next()) {
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
}finally {
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace(
);
if(ps!=null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
* 查询一定时间范围的数据
* @author 2Π
public class Demo08 {
* 将字符串日期转化成long数字
* @param date (格式yyyy-MM-dd hh:mm:ss)
* @return
public static long strDate(String date) {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
return format.parse(date).getTime();
} catch (ParseException e) {
e.printStackTrace();
return 0;
public static void main(String[] args){
Connection conn =null;
PreparedStatement ps =null;
ResultSet rs =null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","000000");
String sqlStr = "select * from tb_user where loginTime>? and loginTime<?";
ps = conn.prepareStatement(sqlStr);
Timestamp start = new Timestamp(strDate("2020-04-24 08:00:00"));
Timestamp end = new Timestamp(strDate("2020-04-24 09:00:00"));
ps.setTimestamp(1, start);
ps.setTimestamp(2, end);
rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("uName")+"==="+rs.getObject("loginTime"));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
}finally {
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
if(ps!=null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
查询结果:

增删改package com.yzx.JDBC01;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;import java.sql.Statement;/** * 利用PreparedS...
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLE...
习惯直接使用JdbcTemplate,对于其他的jdbc工具类就没怎么了解,最近使用查询带in参数时,发现无论怎么传参数,都会抛出异常,感觉jdbcTemplate搞不定了。
查找了资料,发现NamedParameterJdbcTemplate可以解决问题。
下面是NamedParamet...
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.Sim
select * from sys_logs
where substr(concat(createdTime), 1, 10) = #{time}
order by createdTime
temp = new Date();
list = sysLogDao.findLogByDay(new SimpleDateFormat("y
CREATE TABLEdatetest(
idint(11) NOT NULL AUTO_INCREMENT,
brand_namevarchar(100) DEFAULT NULL COMMENT '品牌名称',
model_namevarchar(100) DEFAULT NULL C...
查询方法1
SELECT * FROM tableTest WHERE tableTest.time BETWEEN '2011-01-01' AND '2013-03-03'
查询方法2
SELECT * FROM tableTest WHERE tableTest.time BETWEEN STR_TO_DATE('2011-01-01','%Y-%m-%d') AND
使用数据库连接池C3P0及JDBC技术,并结合JSP、Servlet以及Filter等JavaWeb技术实现数据库中的学生信息数据实现增加、修改、删除、查询等操作。 【需求说明】 (1)学生信息包括:学号、姓名、性别、出生日期、所在院系、爱好、个人简介等信息; (2)分别设计: addStu.jsp、editStu.jsp和stuList.jsp用于实现用户交互; (3)分别设计:SaveStudentServlet、EditStudentServlet、DelStudentServlet和SearchStudentServlet四个Servlet程序,用于实现对学生信息数据的增加、修改、删除、查询等功能。 (4)Filter过滤器解决POST提交方式时的中文乱码问
这是一个比较全面的JavaWeb应用,需要涉及到数据库操作、JSP页面、Servlet程序以及Filter过滤器等多个方面。下面我会分别介绍一下各个方面的实现。
一、数据库连接池C3P0及JDBC技术
1.1 数据库准备
首先需要准备好一个数据库,在本例中我们使用MySQL数据库。创建一个名为student的数据库,并在该数据库中创建一个名为stu_info的表,包含学号、姓名、性别、出生日期、所在院系、爱好、个人简介等信息。
1.2 C3P0连接池配置
使用C3P0连接池可以有效地提高数据库连接的效率和稳定性。在项目中,我们需要在web.xml文件中配置一个参数,用来指定C3P0配置文件的路径。
```xml
<context-param>
<param-name>configLocation</param-name>
<param-value>/WEB-INF/c3p0-config.xml</param-value>
</context-param>
然后在项目的WEB-INF目录下创建一个名为c3p0-config.xml的文件,并在其中进行连接池的配置。
```xml
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/student</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="user">root</property>
<property name="password">123456</property>
<property name="maxPoolSize">50</property>
<property name="minPoolSize">5</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">1800</property>
<property name="acquireIncrement">3</property>
<property name="idleConnectionTestPeriod">60</property>
<property name="checkoutTimeout">10000</property>
</default-config>
</c3p0-config>
1.3 JDBC编程
在JavaWeb应用中,我们需要使用JDBC技术来连接数据库并进行数据的增删改查。在本例中,我们可以使用以下代码来连接数据库并查询学生信息。
```java
public class StudentDao {
private ComboPooledDataSource dataSource;
public StudentDao() throws Exception {
dataSource = new ComboPooledDataSource();
// 获取学生信息
public List<Student> getStudents() {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Student> students = new ArrayList<Student>();
try {
conn = dataSource.getConnection();
String sql = "SELECT * FROM stu_info";
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
while (rs.next()) {
Student student = new Student();
student.setSno(rs.getString("sno"));
student.setName(rs.getString("name"));
student.setSex(rs.getString("sex"));
student.setBirthday(rs.getDate("birthday"));
student.setDepartment(rs.getString("department"));
student.setHobby(rs.getString("hobby"));
student.setIntro(rs.getString("intro"));
students.add(student);
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
return students;
二、JSP页面
在JavaWeb应用中,我们通常需要使用JSP页面来实现前端页面的展示和用户交互。在本例中,我们需要设计三个JSP页面,分别是addStu.jsp、editStu.jsp和stuList.jsp。其中,addStu.jsp页面用来添加学生信息,editStu.jsp页面用来编辑学生信息,stuList.jsp页面用来展示学生信息列表。
addStu.jsp页面代码:
```html
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<meta charset="UTF-8">
<title>添加学生信息</title>
</head>
<h1>添加学生信息</h1>
<form action="${pageContext.request.contextPath}/saveStudent" method="post">
<table>
<td>学号:</td>
<td><input type="text" name="sno"></td>
<td>姓名:</td>
<td><input type="text" name="name"></td>
<td>性别:</td>
<input type="radio" name="sex" value="男">男
<input type="radio" name="sex" value="女">女
<td>出生日期:</td>
<td><input type="date" name="birthday"></td>
<td>所在院系:</td>
<td><input type="text" name="department"></td>
<td>爱好:</td>
<td><input type="text" name="hobby"></td>
<td>个人简介:</td>
<td><textarea name="intro"></textarea></td>
<td colspan="2">
<input type="submit" value="保存">
<input type="reset" value="重置">
</table>
</form>
</body>
</html>
editStu.jsp页面代码:
```html
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<meta charset="UTF-8">
<title>编辑学生信息</title>
</head>
<h1>编辑学生信息</h1>
<form action="${pageContext.request.contextPath}/editStudent" method="post">
<table>
<td>学号:</td>
<td><input type="text" name="sno" value="${student.sno}" readonly></td>
<td>姓名:</td>
<td><input type="text" name="name" value="${student.name}"></td>
<td>性别:</td>
<input type="radio" name="sex" value="男" ${student.sex == '男' ? 'checked' : ''}>男
<input type="radio" name="sex" value="女" ${student.sex == '女' ? 'checked' : ''}>女
<td>出生日期:</td>
<td><input type="date" name="birthday" value="${student.birthday}"></td>
<td>所在院系:</td>
<td><input type="text" name="department" value="${student.department}"></td>
<td>爱好:</td>
<td><input type="text" name="hobby" value="${student.hobby}"></td>
<td>个人简介:</td>
<td><textarea name="intro">${student.intro}</textarea></td>
<td colspan="2">
<input type="submit" value="保存">
<input type="reset" value="重置">
</table>
</form>
</body>
</html>
stuList.jsp页面代码:
```html
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<meta charset="UTF-8">
<title>学生信息列表</title>
</head>
<h1>学生信息列表</h1>
<table border="1">
<th>学号</th>
<th>姓名</th>
<th>性别</th>
<th>出生日期</th>
<th>所在院系</th>
<th>爱好</th>
<th>个人简介</th>
<th>操作</th>
<c:forEach items="${students}" var="student">
<td>${student.sno}</td>
<td>${student.name}</td>
<td>${student.sex}</td>
<td>${student.birthday}</td>
<td>${student.department}</td>
<td>${student.hobby}</td>
<td>${student.intro}</td>
<a href="${pageContext.request.contextPath}/editStu?sno=${student.sno}">编辑</a>
<a href="${pageContext.request.contextPath}/delStudent?sno=${student.sno}">删除</a>
</c:forEach>
</table>
<a href="${pageContext.request.contextPath}/addStu.jsp">添加学生信息</a>
</body>
</html>
三、Servlet程序
在JavaWeb应用中,我们需要使用Servlet程序来处理HTTP请求和响应。在本例中,我们需要设计四个Servlet程序,分别是SaveStudentServlet、EditStudentServlet、DelStudentServlet和SearchStudentServlet。
SaveStudentServlet用来保存学生信息,EditStudentServlet用来编辑学生信息,DelStudentServlet用来删除学生信息,SearchStudentServlet用来查询学生信息。
SaveStudentServlet代码:
```java
public class SaveStudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private StudentDao studentDao;
public SaveStudentServlet() {
super();
public void init() throws ServletException {
try {
studentDao = new StudentDao();
} catch (Exception e) {
e.printStackTrace();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String sno = request.getParameter("sno");
String name = request.getParameter("name");
String sex = request.getParameter("sex");
String birthday = request.getParameter("birthday");
String department = request.getParameter("department");
String hobby = request.getParameter("hobby");
String intro = request.getParameter("intro");
Student student = new Student();
student.setSno(sno);
student.setName(name);
student.setSex(sex);
student.setBirthday(Date.valueOf(birthday));
student.setDepartment(department);
student.setHobby(hobby);
student.setIntro(intro);
try {
studentDao.addStudent(student);
} catch (Exception e) {
e.printStackTrace();
response.sendRedirect(request.getContextPath() + "/stuList");
EditStudentServlet代码:
```java
public class EditStudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private StudentDao studentDao;
public EditStudentServlet() {
super();
public void init() throws ServletException {
try {
studentDao = new StudentDao();
} catch (Exception e) {
e.printStackTrace();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String sno = request.getParameter("sno");
Student student = null;
try {
student = studentDao.getStudent(sno);
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("student", student);
request.getRequestDispatcher("/editStu.jsp").forward(request, response);
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String sno = request.getParameter("sno");
String name = request.getParameter("name");
String sex = request.getParameter("sex");
String birthday = request.getParameter("birthday");
String department = request.getParameter("department");
String hobby = request.getParameter("hobby");
String intro = request.getParameter("intro");
Student student = new Student();
student.setSno(sno);
student.setName(name);
student.setSex(sex);
student.setBirthday(Date.valueOf(birthday));
student.setDepartment(department);
student.setHobby(hobby);
student.setIntro(intro);
try {
studentDao.updateStudent(student);
} catch (Exception e) {
e.printStackTrace();
response.sendRedirect(request.getContextPath() + "/stuList");
DelStudentServlet代码:
```java
public class DelStudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private StudentDao studentDao;
public DelStudentServlet() {
super();
public void init() throws ServletException {
try {
studentDao = new StudentDao();
} catch (Exception e) {
e.printStackTrace();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String sno = request.getParameter("sno");
try {
studentDao.delStudent(sno);
} catch (Exception e) {
e.printStackTrace();
response.sendRedirect(request.getContextPath() + "/stuList");
SearchStudentServlet代码:
```java
public class SearchStudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private StudentDao studentDao;
public SearchStudentServlet() {
super();
public void init() throws ServletException {
try {
studentDao = new StudentDao();
} catch (Exception e) {
e.printStackTrace();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
String keyword = request.getParameter("keyword");
List<Student> students = null;
try {
students = studentDao.searchStudent(keyword);
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("students", students);
request.getRequestDispatcher("/stuList.jsp").forward(request, response);
四、Filter过滤器
在JavaWeb应用中,我们需要使用Filter过滤器来对HTTP请求和响应进行过滤处理。在本例中,我们需要使用Filter过滤器来解决POST提交方式时的中文乱码问题。
Filter过滤器代码:
```java
public class EncodingFilter implements Filter {
private String encoding = "UTF-8";
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
request.setCharacterEncoding(encoding);
response.setCharacterEncoding(encoding);
filterChain.doFilter(request, response);
public void init(FilterConfig filterConfig) throws ServletException {
String encodingParam = filterConfig.getInitParameter("encoding");
if (encodingParam != null) {
encoding = encodingParam;
public void destroy() {
在web.xml文件中配置Filter过滤器:
```xml
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>com.example.EncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
以上就是本例中JavaWeb应用的实现,包括C3P0连接池的配置、JSP页面的设计、Servlet程序的编写以及Filter过滤器的使用。