该项目的结构如下图所示:
打开MySQL,输入默认超级root用户的密码,然后数据库的操作如下代码:
--创建数据库
create database ManageTrain;
--使用数据库
use ManageTrain;
--创建表 车次信息管理表 主键:车次
--属性:车次 出发地 目的地 行车时间 硬座票价 软座票价 硬卧票价 软卧票价 车辆路线
create table TrainManage(
trainid varchar(20) primary key,
start varchar(20),
end varchar(20),
time varchar(20),
yzprice decimal(10,1),
rzprice decimal(10,1),
ywprice decimal(10,1),
rwprice decimal(10,1),
root varchar(200)
);
--插入数据
insert TrainManage (trainid,start,end,time,yzprice,rzprice,ywprice,rwprice,root)
values ("T87","Beijing","Guiyang","28小时","278","320","464.5","550",
"Beijing Shijiazhuang Guiyang");
insert TrainManage (trainid,start,end,time,yzprice,rzprice,ywprice,rwprice,root)
values ("T87","Guiyang","Beijing","28小时","278","320","464.5","550",
"Guiyang Shijiazhuang Beijing");
--查询数据
select * from TrainManage;
注意:上面操作在MySQL黑框中输出增删改查的SQL语言就可以,不要把中文注释也执行。同时设置所有编码方式都统一为utf-8防止乱码,数据库表结构如下图所示: 新建Web Project,项目名为“TrainDatabase”,对火车车次数据库的增删改查。
运行效果如下图所示:
package util;
import java.sql.*;
import com.mysql.jdbc.Driver;
public class JDBCConnect {
//获取默认数据库连接
public static Connection getConnection() throws SQLException {
return getConnection("ManageTrain", "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();
}
}
}
2.在src下新建文件夹bean,然后添加类TrainManage.java。代码如下:
package bean;
public class TrainManage {
private String trainid; //车次
private String start; //出发地
private String end; //目的地
private String time; //行车时间
private float yzprice; //硬座票价
private float rzprice; //软座票价
private float ywprice; //硬卧票价
private float rwprice; //软卧票价
private String root; //车辆路线
public String getTrainid() { return trainid; }
public String getStart() { return start; }
public String getEnd() { return end; }
public String getTime() { return time; }
public Float getYzprice() { return yzprice; }
public Float getRzprice() { return rzprice; }
public Float getYwprice() { return ywprice; }
public Float getRwprice() { return rwprice; }
public String getRoot() { return root; }
public void setTrainid(String str) { this.trainid = str; }
public void setStart(String str) { this.start = str; }
public void setEnd(String str) { this.end = str; }
public void setTime(String str) { this.time = str; }
public void setYzprice(Float price) { this.yzprice = price; }
public void setRzprice(Float price) { this.rzprice = price; }
public void setYwprice(Float price) { this.ywprice = price; }
public void setRwprice(Float price) { this.rwprice = price; }
public void setRoot(String str) { this.root = str; }
}
3.在src下新建文件夹DAO,然后添加类StudentDAO.java。代码如下:通常DAO(Data Access Object)数据访问对象是负责与数据库连接,主要功能执行对数据表的CUDR操作(创建、更新、删除、查询)。每个数据表都定义一个DAO接口或类实现,实现对此表的读写操作。换句话说,就是在域名.项目.模块.dao文件夹下创建个DAO类即可。
package DAO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import bean.TrainManage;
import util.JDBCConnect;
public class TrainManageDAO {
//插入车次
public static int insert(TrainManage train) throws Exception {
String sql = "INSERT INTO TrainManage (trainid,start,end,time,yzprice,rzprice,ywprice,rwprice,root) " +
"VALUES ('" + train.getTrainid() +"','"+ train.getStart() +"','"+ train.getEnd() +
"','"+ train.getTime() +"','"+ train.getYzprice() +"','"+ train.getRzprice() +
"','"+ train.getYwprice() +"','"+ train.getRwprice() +"','"+ train.getRoot() +"');";
System.out.println(sql);
return JDBCConnect.executeUpdate(sql);
/**
* 总是报错 No value specified for parameter 5
* 很多原因是 insert into train (?,?,?) values (?,?,?) 前面不应该是问号
* 但我的怀疑是参数过多使用executeUpdate(sql,?,?,?...)方法是错误
*
* String sql = "INSERT INTO TrainManage (trainid,start,end,time,yzprice,rzprice,ywprice,rwprice,root) VALUES (?,?,?,?,?,?,?,?,?);";
* System.out.println(sql);
* return JDBCConnect.executeUpdate(sql, train.getTrainid(), train.getStart(), train.getEnd(),
* train.getTime(), train.getYzprice(), train.getRzprice(), train.getYwprice(),
* train.getRwprice(), train.getRoot());
*/
}
//更新车次
public static int update(TrainManage train) throws Exception {
String sql = "UPDATE TrainManage SET start = ?, end = ? WHERE trainid = ? ";
return JDBCConnect.executeUpdate(sql, train.getStart(), train.getEnd(), train.getTrainid());
}
//删除操作
public static int delete(String id) throws Exception {
String sql = "DELETE FROM TrainManage WHERE trainid = ? ";
return JDBCConnect.executeUpdate(sql, id);
}
//查找记录 某车次
public static TrainManage find(String id) throws Exception {
String sql = "SELECT * FROM TrainManage WHERE trainid = ? ";
Connection conn = null;
PreparedStatement preStmt = null;
ResultSet rs = null;
try {
//链接数据库执行SQL语句
conn = JDBCConnect.getConnection(); //连接默认数据库
preStmt = conn.prepareStatement(sql);
preStmt.setString(1, id);
rs = preStmt.executeQuery();
//获取查询结果
if (rs.next()) {
TrainManage train = new TrainManage();
train.setTrainid(rs.getString("trainid"));
train.setStart(rs.getString("start"));
train.setEnd(rs.getString("end"));
train.setTime(rs.getString("time"));
train.setYzprice(rs.getFloat("yzprice"));
train.setYwprice(rs.getFloat("ywprice"));
train.setRzprice(rs.getFloat("rzprice"));
train.setRwprice(rs.getFloat("rwprice"));
train.setRoot(rs.getString("root"));
return train;
} else {
return null;
}
} finally { //依次关闭 记录集 声明 连接对象
if (rs != null)
rs.close();
if (preStmt != null)
preStmt.close();
if (conn != null)
conn.close();
}
}
//查找记录 起始站 达到站
public static List findStartEnd(String start,String end) throws Exception {
List list = new ArrayList();
String sql = null;
Connection conn = null;
Statement statement = null;
ResultSet rs = null;
//判断SQL语句
if(start==""&&end=="") {
sql = "SELECT * FROM TrainManage;";
} else if(end=="") {
sql = "SELECT * FROM TrainManage WHERE start = '"+ start + "';";
} else if(start=="") {
sql = "SELECT * FROM TrainManage WHERE end = '"+ end + "';";
} else {
sql = "SELECT * FROM TrainManage WHERE start = '"
+ start + "' and end = '"+ end +"';";
}
//执行
try {
//链接数据库执行SQL语句
conn = JDBCConnect.getConnection(); //连接默认数据库
statement = conn.createStatement();
System.out.println(start+" "+end);
System.out.println(sql);
rs = statement.executeQuery(sql);
//获取查询结果
while(rs.next()) {
TrainManage train = new TrainManage();
train.setTrainid(rs.getString("trainid"));
train.setStart(rs.getString("start"));
train.setEnd(rs.getString("end"));
train.setTime(rs.getString("time"));
train.setYzprice(rs.getFloat("yzprice"));
train.setYwprice(rs.getFloat("ywprice"));
train.setRzprice(rs.getFloat("rzprice"));
train.setRwprice(rs.getFloat("rwprice"));
train.setRoot(rs.getString("root"));
list.add(train);
}
} catch (Exception e) {
System.out.println("错误:"+e.getMessage());
}
finally { //依次关闭 记录集 声明 连接对象
if (rs != null)
rs.close();
if (statement != null)
statement.close();
if (conn != null)
conn.close();
}
return list;
}
//查询所有车次信息
public static List listStudents() throws Exception {
List list = new ArrayList();
String sql = "SELECT * FROM TrainManage";
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.
TrainManage train = new TrainManage();
train.setTrainid(rs.getString("trainid"));
train.setStart(rs.getString("start"));
train.setEnd(rs.getString("end"));
train.setTime(rs.getString("time"));
train.setYzprice(rs.getFloat("yzprice"));
train.setYwprice(rs.getFloat("ywprice"));
train.setRzprice(rs.getFloat("rzprice"));
train.setRwprice(rs.getFloat("rwprice"));
train.setRoot(rs.getString("root"));
list.add(train);
}
} finally {
if (rs != null)
rs.close();
if (preStmt != null)
preStmt.close();
if (conn != null)
conn.close();
}
return list;
}
}
4.在WebRoot文件夹下创建trainManage.jsp文件,页面布局代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
List trainList = TrainManageDAO.listStudents();
request.setAttribute("trainList", trainList);
%>
火车卡订票系统管理系统
5在WebRoot路径下创建image文件夹,并添加jsp中需要使用的图片资源。
<%
List trainList = TrainManageDAO.listStudents();
request.setAttribute("trainList", trainList);
%>
...
火车列次 出发地 目的地 行车时间
硬座票价 软座票价 硬卧票价 软卧票价
车辆路线 信息操作
${train.trainid}
${train.start}
${train.end}
${train.time}
${train.yzprice}
${train.rzprice}
${train.ywprice}
${train.rwprice}
查看
修改
删除
关键字查询运行截图如下图所示:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String mstart = request.getParameter("start");
String mend = request.getParameter("end");
List trainList = TrainManageDAO.findStartEnd(mstart,mend);
//List trainList = TrainManageDAO.listStudents();
request.setAttribute("trainList", trainList);
%>
火车卡订票系统管理系统
调用的trainManageDAO.java中的函数findStartEnd(String start,String end)如下,它如果不输入则进行所有查找,也支持单方面出发或到达查找://查找记录 某车次
public static List findStartEnd(String start,String end) throws Exception {
List list = new ArrayList();
String sql = null;
Connection conn = null;
Statement statement = null;
ResultSet rs = null;
//判断SQL语句
if(start==""&&end=="") {
sql = "SELECT * FROM TrainManage;";
} else if(end=="") {
sql = "SELECT * FROM TrainManage WHERE start = '"+ start + "';";
} else if(start=="") {
sql = "SELECT * FROM TrainManage WHERE end = '"+ end + "';";
} else {
sql = "SELECT * FROM TrainManage WHERE start = '"
+ start + "' and end = '"+ end +"';";
}
//执行
try {
//链接数据库执行SQL语句
conn = JDBCConnect.getConnection(); //连接默认数据库
statement = conn.createStatement();
System.out.println(start+" "+end);
System.out.println(sql);
rs = statement.executeQuery(sql);
//获取查询结果
while(rs.next()) {
TrainManage train = new TrainManage();
train.setTrainid(rs.getString("trainid"));
train.setStart(rs.getString("start"));
train.setEnd(rs.getString("end"));
train.setTime(rs.getString("time"));
train.setYzprice(rs.getFloat("yzprice"));
train.setYwprice(rs.getFloat("ywprice"));
train.setRzprice(rs.getFloat("rzprice"));
train.setRwprice(rs.getFloat("rwprice"));
train.setRoot(rs.getString("root"));
list.add(train);
}
} catch (Exception e) {
System.out.println("错误:"+e.getMessage());
}
finally { //依次关闭 记录集 声明 连接对象
if (rs != null)
rs.close();
if (statement != null)
statement.close();
if (conn != null)
conn.close();
}
return list;
}
其中核心步骤如下:String sql = "SELECT * FROM TrainManage WHERE start = ? and end = ? ;";
Connection conn = JDBCConnect.getConnection(); //连接默认数据库
PreparedStatement preStmt = conn.prepareStatement(sql);
preStmt.setString(1, start);
preStmt.setString(2, end);
ResultSet rs = preStmt.executeQuery();
但是在查询英文Beijing => Guizhou 时能正确显示,而中文就没有结果,后改为带引号("'"+string+"'")的参数方式,核心代码如下:
String sql = "SELECT * FROM TrainManage WHERE start = '"
+ start + "' and end = '"+ end +"';";
Connection conn = JDBCConnect.getConnection(); //连接默认数据库
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(sql);
while(rs.next()){...}
后来使用该方法仍然存在乱码,但是这次我发现了原因,在form提交表单时采用Get方法就会出现中文乱码,虽然URL中显示的是: 该部分运行截图如下图所示:
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import bean.TrainManage;
import util.JDBCConnect;
import DAO.TrainManageDAO;
public class InsertTrainAction extends HttpServlet {
public InsertTrainAction() {
super();
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
//The doGet method of the servlet
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("");
out.println("");
out.println(" A Servlet ");
out.println(" ");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" ");
out.println("");
out.flush();
out.close();
}
//The doPost method of the servlet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8"); //设置输出编码
request.setCharacterEncoding("UTF-8");
try {
//插入数据库
String m_trainid = request.getParameter("trainid");
String m_start = request.getParameter("start");
String m_end = request.getParameter("end");
String m_time = request.getParameter("time");
String m_yz = request.getParameter("yzprice");
Float m_yzprice = Float.parseFloat(m_yz);
String m_rz = request.getParameter("rzprice");
Float m_rzprice = Float.parseFloat(m_rz);
String m_yw = request.getParameter("ywprice");
Float m_ywprice = Float.parseFloat(m_yw);
String m_rw = request.getParameter("rwprice");
Float m_rwprice = Float.parseFloat(m_rw);
String m_root = request.getParameter("root");
TrainManage train = new TrainManage();
train.setTrainid(m_trainid);
train.setStart(m_start);
train.setEnd(m_end);
train.setTime(m_time);
train.setYzprice(m_yzprice);
train.setRzprice(m_rzprice);
train.setYwprice(m_ywprice);
train.setRwprice(m_rwprice);
train.setRoot(m_root);
int success = TrainManageDAO.insert(train);
request.setAttribute("success", success);
//设置全路径 否则trainManage.jsp跳转到servlet/trainManage.jsp路径下不存在
response.sendRedirect("http://localhost:8080/TrainDatabase/trainManage.jsp");
} catch(Exception e) {
System.out.println("错误:"+e.getMessage());
response.sendRedirect("http://localhost:8080/TrainDatabase/trainManage.jsp");
}
}
public void init() throws ServletException {
// Put your code here
}
}
它会自动配置WebRoot/WEB-INF/web.xml文件中servlet和其映射。同时在WebRoot中添加trainManageInsert.jsp。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session = "true" %>
火车卡订票系统管理系统
该方法不同于前面的,它是通过Servlet实现的。主要是在采用JSP调用DAO中插入操作总是失败,其流程如下: 运行效果如下图所示,点击删除后弹出提示框“确定”后删除:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session = "true" %>
<%
String action = request.getParameter("action");
String id = request.getParameter("id");
if(id == null || id==""){ out.println("没有选中删除的车次"); return; }
if("del".equals(action)){
int isDelete = TrainManageDAO.delete(id);
request.setAttribute("isDelete", isDelete);
}
%>
火车卡订票系统管理系统
删除的核心代码如下: 具体流程是:首先点击修改,通过超链传递trainid(火车车次)到修改界面,然后通过调用trainManageDAO.java中find查找该车次的所有信息并显示。再通过提交POST及Servlet到UpdateTrainAction.java中,在doPost方法中调用DAO中update(TrainMManage)实现更新。其中运行结果如下图所示:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session = "true" %>
<%
String action = request.getParameter("action");
String id = request.getParameter("id");
TrainManage train = TrainManageDAO.find(id);
request.setAttribute("train", train);
%>
火车卡订票系统管理系统
然后再src/servlet中创建Servlet类,即UpdateTrainAction.java文件。代码如下:package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import DAO.TrainManageDAO;
import bean.TrainManage;
public class UpdateTrainAction extends HttpServlet {
public UpdateTrainAction() {
super();
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
//The doGet method of the servlet.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("");
out.println("");
out.println(" A Servlet ");
out.println(" ");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" ");
out.println("");
out.flush();
out.close();
}
//The doPost method of the servlet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8"); //设置输出编码
request.setCharacterEncoding("UTF-8");
try {
//更新数据库
String m_trainid = request.getParameter("trainid");
String m_start = request.getParameter("start");
String m_end = request.getParameter("end");
String m_time = request.getParameter("time");
String m_yz = request.getParameter("yzprice");
Float m_yzprice = Float.parseFloat(m_yz);
String m_rz = request.getParameter("rzprice");
Float m_rzprice = Float.parseFloat(m_rz);
String m_yw = request.getParameter("ywprice");
Float m_ywprice = Float.parseFloat(m_yw);
String m_rw = request.getParameter("rwprice");
Float m_rwprice = Float.parseFloat(m_rw);
String m_root = request.getParameter("root");
TrainManage train = new TrainManage();
train.setTrainid(m_trainid);
train.setStart(m_start);
train.setEnd(m_end);
train.setTime(m_time);
train.setYzprice(m_yzprice);
train.setRzprice(m_rzprice);
train.setYwprice(m_ywprice);
train.setRwprice(m_rwprice);
train.setRoot(m_root);
int success = TrainManageDAO.update(train);
request.setAttribute("success", success);
//设置全路径 否则trainManage.jsp跳转到servlet/trainManage.jsp路径下不存在
response.sendRedirect("http://localhost:8080/TrainDatabase/trainManage.jsp");
} catch(Exception e) {
System.out.println("错误:"+e.getMessage());
response.sendRedirect("http://localhost:8080/TrainDatabase/trainManage.jsp");
}
}
public void init() throws ServletException {
// Put your code here
}
}
你可能发现,update函数只修改了start和end,其它你可以自己添加,方法类似。同时如果参数过多建议使用下面的方法替代:public static int update(TrainManage train) throws Exception {
/**
* String sql = "UPDATE TrainManage SET start = ?, end = ? WHERE trainid = ? ";
* return JDBCConnect.executeUpdate(sql, train.getStart(), train.getEnd(), train.getTrainid());
*/
String sql = "UPDATE TrainManage SET start = '"+ train.getStart() +
"', end = '" + train.getEnd() + "' WHERE trainid = '" + train.getTrainid() +"';";
System.out.println(sql);
return JDBCConnect.executeUpdate(sql);
}
还有一个查看详情就不介绍了,参看源代码吧~
最后文章就不总结了,因为每步都讲得非常清楚,无论是步骤、思想,还是源代码截图。作者真的很用心的写这篇文章,从晚上8点写到了凌晨5点,中间打了两把dota2。一方面由于我也认为这些都非常重要又基础,另一方面为哪些初学者做Java网站的。
最后希望文章对你有所帮助!如果文章有错误或不足之处,还请海涵~真的有点累了睡了。有时候想想值不值得这样写文章,心安虽好但对身体不好。