簡單對MySQL 操作
先上個動圖了解一下本章的意圖。

首先創(chuàng)建一個jsp項(xiàng)目 MySQLDBDemo
準(zhǔn)備兩個jar包
數(shù)據(jù)庫jar包
mysql-connector-java-5.0.8-bin.jar (自行網(wǎng)上下載)
servlet-api.jar (從tomcat lib內(nèi)獲取)
WebContent
-- Web-INT
-- lib (放于這個文件夾內(nèi))
構(gòu)建index.jsp 頁面
<%@ 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=ISO-8859-1">
<title>MySQL Action</title>
<style type="text/css">
.action {
width: 500px;
height: 200px;
margin: 0 auto;
background: rgba(234, 233, 233, 0.22);
margin-top: 50px;
}
.result {
width: 500px;
height: 100px;
margin: 0 auto;
background: rgba(189, 187, 104, 0.22);
margin-top: 50px;
}
.action li {
list-style: none;
padding-top: 20px;
}
</style>
</head>
<body>
<div class="action">
<div>JSP MySQL 簡單的增刪改查</div>
<ul>
<li><a href="/MySQLDBDemo/InsertServlet">Insert</a></li>
<li><a href="/MySQLDBDemo/SelectServlet">Select</a></li>
<li><a href="/MySQLDBDemo/UpdateServlet">Update</a></li>
<li><a href="/MySQLDBDemo/DeleteServlet">Delete</a></li>
</ul>
</div>
<div class="result">
<div>Result:</div>
<div>${message}</div>
<div>${studentid}</div>
<div>${quiz}</div>
<div>${exam}</div>
</div>
</body>
</html>
這一部分表示,點(diǎn)擊鏈接觸發(fā)servlet 執(zhí)行相關(guān)的操作
<div class="action">
<div>JSP MySQL 簡單的增刪改查</div>
<ul>
<li><a href="/MySQLDBDemo/InsertServlet">Insert</a></li>
<li><a href="/MySQLDBDemo/SelectServlet">Select</a></li>
<li><a href="/MySQLDBDemo/UpdateServlet">Update</a></li>
<li><a href="/MySQLDBDemo/DeleteServlet">Delete</a></li>
</ul>
</div>
這一部分用于servlet傳遞的參數(shù),顯示 操作結(jié)果
<div class="result">
<div>Result:</div>
<div>${message}</div>
<div>${studentid}</div>
<div>${quiz}</div>
<div>${exam}</div>
</div>
index.jsp 頁面 非常簡單。

建立一個簡單的數(shù)據(jù)庫鏈接類 MyDBUtil.java
方便servlet 去鏈接數(shù)據(jù)庫
package cn.crabshell.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MyDBUtil {
/**
* @param args
*/
// 驅(qū)動程序就是之前在classpath中配置的JDBC的驅(qū)動程序的JAR 包中
public static final String DBDRIVER = "com.mysql.jdbc.Driver";
// 連接地址是由各個數(shù)據(jù)庫生產(chǎn)商單獨(dú)提供的,所以需要單獨(dú)記住
public static final String DBURL = "jdbc:mysql://localhost:3306/student";
// 連接數(shù)據(jù)庫的用戶名
public static final String DBUSER = "root";
// 連接數(shù)據(jù)庫的密碼
public static final String DBPASS = "";
static Connection conn;
/**
* Connect to DB
*
* @return Connection
* @throws SQLException
*/
public static Connection connetDB(){
// 1、使用CLASS 類加載驅(qū)動程序
try {
Class.forName(DBDRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
} catch (SQLException e) {
//e.printStackTrace();
return null;
}
return conn;
}
/**
* close DB
*/
public static void closeDB() {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
說明:
public static final String DBURL = "jdbc:mysql://localhost:3306/student";
// 連接數(shù)據(jù)庫的用戶名
public static final String DBUSER = "root";
// 連接數(shù)據(jù)庫的密碼
public static final String DBPASS = "";
student 是在你的mysql內(nèi)創(chuàng)建的數(shù)據(jù)庫名稱。
作者的本地實(shí)驗(yàn)數(shù)據(jù)庫賬號是 root, 密碼是空。
建立數(shù)據(jù)庫 student 后,
可以執(zhí)行 sql 語句創(chuàng)建 一張表 grade
CREATE TABLE `student`.`grade` ( `id` INT NOT NULL AUTO_INCREMENT ,
`studentid` VARCHAR(11) NOT NULL , `quiz` INT(255) NOT NULL , `exam`
INT(255) NOT NULL , PRIMARY KEY (`id`)) ;

編碼 servlet
創(chuàng)建 InsertServlet.java
在 doGet() 方法內(nèi) 添加 下面代碼
代碼 鏈接了數(shù)據(jù)庫,并向數(shù)據(jù)庫插入一條數(shù)據(jù)。
插入數(shù)據(jù)之后,返回一個int值, 0表示失敗,1表示插入成功。
將參數(shù)傳遞給index.jsp頁面, 顯示結(jié)果。
String sql = "INSERT INTO grade (studentid,quiz,exam) VALUES(?,?,?)";
PreparedStatement ps = null;
Connection conn = MyDBUtil.connetDB(); // get db connection
int result = 0;
try {
ps = conn.prepareStatement(sql);
ps.setString(1, "b63030007");
ps.setInt(2, 99);
ps.setInt(3, 99);
result = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
MyDBUtil.closeDB();
}
String message = null;
if(result == 0){
message = "INSERT FAIL";
}else{
message = "INSERT SUCCESS";
}
request.setAttribute("message", message);
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
創(chuàng)建 SelectServlet.java
在 doGet() 方法內(nèi) 添加 下面代碼
代碼 鏈接了數(shù)據(jù)庫,并向數(shù)據(jù)庫查詢數(shù)據(jù)。
如果結(jié)果集有數(shù)據(jù),就給 studentid,quiz,exam賦值。
將參數(shù)傳遞給index.jsp頁面, 顯示結(jié)果。
Connection conn = MyDBUtil.connetDB(); // get db connection;
PreparedStatement ps = null;
ResultSet rs = null;
String studentid = null;
String quiz = null;
String exam = null;
String sql = "select * from grade where studentid = ? limit 1";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, "b63030007");
rs = ps.executeQuery();
while (rs.next()) {
studentid = rs.getString("studentid");
quiz = rs.getString("quiz");
exam = rs.getString("exam");
}
} catch (SQLException e) {
e.printStackTrace();
}
String message = null;
if(studentid == null){
message = "Select FAIL";
}else{
message = "Select SUCCESS";
request.setAttribute("studentid", studentid);
request.setAttribute("quiz", quiz);
request.setAttribute("exam", exam);
}
request.setAttribute("message", message);
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
創(chuàng)建 UpdateServlet.java
在 doGet() 方法內(nèi) 添加 下面代碼
代碼 鏈接了數(shù)據(jù)庫,并向數(shù)據(jù)庫更新數(shù)據(jù)。
給指定 studentid 更改 quiz 和 exam的值。
更新數(shù)據(jù)之后,返回一個int值, 0表示失敗,1表示插入成功。
將參數(shù)傳遞給index.jsp頁面, 顯示結(jié)果。
String sql = "UPDATE grade SET quiz=?,exam=? WHERE studentid=?";
PreparedStatement ps = null;
Connection conn = MyDBUtil.connetDB(); // get db connection
int result = 0;
try {
ps = conn.prepareStatement(sql);
ps.setInt(1, 100);
ps.setInt(2, 100);
ps.setString(3, "b63030007");
result = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
MyDBUtil.closeDB();
}
String message = null;
if(result == 0){
message = "UPDATE FAIL";
}else{
message = "UPDATE SUCCESS";
}
request.setAttribute("message", message);
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
創(chuàng)建 DeleteServlet.java
在 doGet() 方法內(nèi) 添加 下面代碼
代碼 鏈接了數(shù)據(jù)庫,并向給指定 studentid 刪除數(shù)據(jù)。
刪除數(shù)據(jù)之后,返回一個int值, 0表示失敗,1表示插入成功。
將參數(shù)傳遞給index.jsp頁面, 顯示結(jié)果。
String sql = "DELETE FROM grade WHERE studentid = ?";
PreparedStatement ps = null;
Connection conn = MyDBUtil.connetDB(); // get db connection
int result = 0;
try {
ps = conn.prepareStatement(sql);
ps.setString(1, "b63030007");
result = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
MyDBUtil.closeDB();
}
String message = null;
if(result == 0){
message = "DELETE FAIL";
}else{
message = "DELETE SUCCESS";
}
request.setAttribute("message", message);
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);