通過JDBC對mysql數據庫進行增刪改查
摘要
本文提供了一個簡單的java實例,利用JDBC,實現了對mysql數據庫的增刪改查操作,並提供了完整代碼見附錄。
一、準備工作
本文使用的編譯器爲IDEA2018.2,可參考
在IDEA中建立一個簡單的JDBC項目。
二、涉及的java知識點
可參考Java Api手冊
Connection
與特定數據庫的連接(會話)。在連接上下文中執行 SQL 語句並返回結果。
Connection 對象的數據庫能夠提供描述其表、所支持的 SQL 語法、存儲過程、此連接功能等等的信息。
相關方法 | 描述 |
---|---|
prepareStatement() | 創建一個 PreparedStatement 對象來將參數化的 SQL 語句發送到數據庫。 |
close() | 立即釋放此 Connection 對象的數據庫和 JDBC 資源,而不是等待它們被自動釋放。 |
DriverManager.getConnection() | 試圖建立到給定數據庫 URL 的連接。DriverManager 試圖從已註冊的 JDBC 驅動程序集中選擇一個適當的驅動程序 |
ResultSet
表示數據庫結果集的數據表,通常通過執行查詢數據庫的語句生成。
相關方法 | 描述 |
---|---|
next() | 將光標從當前位置向前移一行。 |
getString() | 以 Java 編程語言中 String 的形式獲取此 ResultSet 對象的當前行中指定列的值。 |
getInt() | 以 Java 編程語言中 int的形式獲取此 ResultSet 對象的當前行中指定列的值。 |
close(); | 立即釋放此 ResultSet 對象的數據庫和 JDBC 資源,而不是等待該對象自動關閉時發生此操作。 |
PreparedStatement
表示預編譯的 SQL 語句的對象。
SQL 語句被預編譯並存儲在 PreparedStatement 對象中。然後可以使用此對象多次高效地執行該語句。
注:用於設置 IN 參數值的設置方法(setShort、setString 等等)必須指定與輸入參數的已定義 SQL 類型兼容的類型。例如,如果 IN 參數具有 SQL 類型 INTEGER,那麼應該使用 setInt 方法。
如果需要任意參數類型轉換,使用 setObject 方法時應該將目標 SQL 類型作爲其參數。
在以下設置參數的示例中,con 表示一個活動連接:
PreparedStatement pstmt = con.prepareStatement(“UPDATE EMPLOYEES SET SALARY = ? WHERE ID = ?”);
pstmt.setBigDecimal(1, 153833.00)
pstmt.setInt(2, 110592)
相關方法 | 描述 |
---|---|
setString() | 將指定參數設置爲給定 Java String 值。 |
setInt() | 將指定參數設置爲給定 Java int 值。 |
executeQuery() | 在此 PreparedStatement 對象中執行 SQL 查詢,並返回該查詢生成的 ResultSet 對象。 |
executeUpdate() | 在此 PreparedStatement 對象中執行 SQL 語句,該語句必須是一個 SQL 數據操作語言(Data Manipulation Language,DML)語句,比如 INSERT、UPDATE 或 DELETE 語句;或者是無返回內容的 SQL 語句,比如 DDL 語句。 |
ArrayList
List 接口的大小可變數組的實現。實現了所有可選列表操作,並允許包括 null 在內的所有元素。除了實現 List 接口外,此類還提供一些方法來操作內部用來存儲列表的數組的大小。(此類大致上等同於 Vector 類,除了此類是不同步的。)
相關方法 | 描述 |
---|---|
add(E e) | 將指定的元素添加到此列表的尾部。 |
get(int index) | 返回此列表中指定位置上的元素。 |
size() | 返回此列表中的元素數。 |
三、代碼目錄結構解釋
package名稱 | 解釋 | 包含的java類 |
---|---|---|
bean | 實體層,與數據庫中的表對應 | UserInfo |
dao | 持久層,數據庫增刪改查操作 | UserInfoDao |
util | 工具,數據庫的連接 | DBUtil |
四、實體類的建立
爲了與數據庫中數據對應,我們建立一個與數據庫中表結構一樣的實體類。
一個實體類應該包含以下內容:
1.數據成員變量
2.數據操作方法(Getter,Setter,toString等)
3.構造函數
首先創建與表中字段類型數據類型相同的私有成員變量,然後爲其創建Getter、Setter方法和構造函數。
本文數據庫中的userinfo表中包含的字段爲id(INT),username(VARCHAR),password(VARCHAR),故創建Userinfo實體類如下
public class UserInfo {
//ID,用戶名,密碼
private int id;
private String username;
private String password;
public UserInfo() {
}
//用ID,用戶名,密碼構造
public UserInfo(int id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
//爲私有成員變量創建Getter方法和Setter方法,可通過右鍵點擊Generate自動創建
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
//右鍵點擊Generate,自動生成toString()方法
@Override
public String toString() {
return "UserInfo{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
五、數據庫的連接和關閉
爲了降低代碼的耦合度,提高程序的可複用性,本文將數據庫的連接操作提取出來,封裝到了DBUtil類的靜態方法中。當數據庫操作需要進行數據庫連接操作時,只需要調用DBUtil.getConnection()方法即可,不需要考慮其內部具體實現,且對該方法的修改不會影響外部的代碼,降低了代碼耦合性。
本文這裏只實現了最簡單的連接方式,若想提高性格,可考慮採用數據庫連接池對DBUtil.getConnection()方法進行改進。
5.1數據庫的連接
public static Connection getConnection(){
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/user?useSSL=true&characterEncoding=utf-8&user=root&password=root");
// System.out.println("創建連接成功");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
5.2關閉連接
public static void close(ResultSet rs,Statement statement,Connection connection){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement!=null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
六、JDBC基本操作
爲了對數據進行操作,本文爲此定義了操作類UserinfoDao,並將所有對數據庫操作的sql語句封裝到該類中。
6.1 增加操作
public void add(UserInfo userInfo){
PreparedStatement statement = null;
Connection connection = null;
String sql = "insert into userinfo (id,username,password) values(?,?,?)";
try {
connection = DBUtil.getConnection();
statement=connection.prepareStatement(sql);
statement.setInt(1,userInfo.getId());
statement.setString(2,userInfo.getUsername());
statement.setString(3,userInfo.getPassword());
statement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.close(null, statement, connection);
}
}
6.2 刪除操作
//根據用戶名刪除用戶
public void deleteFromUsername(String username){
PreparedStatement statement = null;
Connection connection = null;
String sql="delete from userinfo where username='"+username+"'";
try {
connection = DBUtil.getConnection();
statement=connection.prepareStatement(sql);
statement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.close(null, statement, connection);
}
}
6.3 修改操作
public int update(UserInfo userInfo){
PreparedStatement statement = null;
Connection connection = null;
String sql="update userinfo set username='"
+userInfo.getUsername()
+"',password='"
+userInfo.getPassword()
+"' where id='"
+userInfo.getId()
+"'";
try {
connection = DBUtil.getConnection();
statement=connection.prepareStatement(sql);
statement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.close(null, statement, connection);
}
}
6.4 查找操作
查找所有用戶
public List<UserInfo> findAll() {
ResultSet rs = null;
Connection connection = null;
PreparedStatement statement = null;
List<UserInfo> list = new ArrayList<>();
try {
connection = DBUtil.getConnection();
//寫sql
String sql = "select * from userinfo";
//得到statement對象執行sql
statement = connection.prepareStatement(sql);
//得到結果集
rs = statement.executeQuery();
//處理結果集
while (rs.next()) {
UserInfo userInfo = new UserInfo();
userInfo.setId(rs.getInt(1));
userInfo.setUsername(rs.getString(2));
userInfo.setPassword(rs.getString(3));
list.add(userInfo);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//關閉
DBUtil.close(rs, statement, connection);
}
return list;
}
根據用戶名查找用戶
//根據用戶名查找用戶
public List<UserInfo> selectFromUsername(String username){
ResultSet rs = null;
Connection connection = null;
PreparedStatement statement = null;
List<UserInfo> list = new ArrayList<>();
try {
connection = DBUtil.getConnection();
//寫sql
String sql = "select * from userinfo where username = '"+username+"'";
//得到statement對象執行sql
statement = connection.prepareStatement(sql);
//得到結果集
rs = statement.executeQuery();
//處理結果集
while (rs.next()) {
UserInfo userInfo = new UserInfo();
userInfo.setId(rs.getInt(1));
userInfo.setUsername(rs.getString(2));
userInfo.setPassword(rs.getString(3));
list.add(userInfo);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//關閉
DBUtil.close(rs, statement, connection);
}
return list;
}
七、測試類的實現
本文在主函數中對上述操作進行了測試。
//Main.java
import bean.UserInfo;
import dao.UserInfoDao;
public class Main {
public static void main(String[] args) {
//查找全部
System.out.println("查找全部");
System.out.println(new UserInfoDao().findAll());
//增加
System.out.println("增加");
new UserInfoDao().add(new UserInfo(10,"王五","王五的密碼"));
System.out.println(new UserInfoDao().findAll());
//更新
System.out.println("更新");
new UserInfoDao().update(new UserInfo(10,"張三","張三的密碼"));
System.out.println(new UserInfoDao().findAll());
//按照用戶名查找
System.out.println("按照用戶名查找");
System.out.println(new UserInfoDao().selectFromUsername("張三"));
//按照ID進行刪除
System.out.println("按照ID刪除");
new UserInfoDao().deleteFromUsername("張三");
System.out.println(new UserInfoDao().findAll());
}
}
測試結果如下,可以看到增刪改查操作運行成功。
附錄
代碼目錄結構如下
UserInfo.java
//UserInfo.java
package bean;
//實體類,對應數據庫中的表結構
public class UserInfo {
//ID,用戶名,密碼
private int id;
private String username;
private String password;
public UserInfo() {
}
//用ID,用戶名,密碼構造
public UserInfo(int id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
//爲私有成員變量創建Getter方法和Setter方法,可通過右鍵點擊Generate自動創建
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
//右鍵點擊Generate,自動生成toString()方法
@Override
public String toString() {
return "UserInfo{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
UserInfoDao.java
//UserInfoDao.java
package dao;
import bean.UserInfo;
import util.DBUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class UserInfoDao {
//select查找所有用戶
public List<UserInfo> findAll() {
ResultSet rs = null;
Connection connection = null;
PreparedStatement statement = null;
List<UserInfo> list = new ArrayList<>();
try {
connection = DBUtil.getConnection();
//寫sql
String sql = "select * from userinfo";
//得到statement對象執行sql
statement = connection.prepareStatement(sql);
//得到結果集
rs = statement.executeQuery();
//處理結果集
while (rs.next()) {
UserInfo userInfo = new UserInfo();
userInfo.setId(rs.getInt(1));
userInfo.setUsername(rs.getString(2));
userInfo.setPassword(rs.getString(3));
list.add(userInfo);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//關閉
DBUtil.close(rs, statement, connection);
}
return list;
}
//添加用戶信息
public void add(UserInfo userInfo){
PreparedStatement statement = null;
Connection connection = null;
String sql = "insert into userinfo (id,username,password) values(?,?,?)";
try {
connection = DBUtil.getConnection();
statement=connection.prepareStatement(sql);
statement.setInt(1,userInfo.getId());
statement.setString(2,userInfo.getUsername());
statement.setString(3,userInfo.getPassword());
statement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.close(null, statement, connection);
}
}
//更新用戶信息
public int update(UserInfo userInfo){
PreparedStatement statement = null;
Connection connection = null;
String sql="update userinfo set username='"
+userInfo.getUsername()
+"',password='"
+userInfo.getPassword()
+"' where id='"
+userInfo.getId()
+"'";
try {
connection = DBUtil.getConnection();
statement=connection.prepareStatement(sql);
statement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.close(null, statement, connection);
}
}
//根據用戶名刪除用戶
public void deleteFromUsername(String username){
PreparedStatement statement = null;
Connection connection = null;
String sql="delete from userinfo where username='"+username+"'";
try {
connection = DBUtil.getConnection();
statement=connection.prepareStatement(sql);
statement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.close(null, statement, connection);
}
}
//根據用戶名查找用戶
public List<UserInfo> selectFromUsername(String username){
ResultSet rs = null;
Connection connection = null;
PreparedStatement statement = null;
List<UserInfo> list = new ArrayList<>();
try {
connection = DBUtil.getConnection();
//寫sql
String sql = "select * from userinfo where username = '"+username+"'";
//得到statement對象執行sql
statement = connection.prepareStatement(sql);
//得到結果集
rs = statement.executeQuery();
//處理結果集
while (rs.next()) {
UserInfo userInfo = new UserInfo();
userInfo.setId(rs.getInt(1));
userInfo.setUsername(rs.getString(2));
userInfo.setPassword(rs.getString(3));
list.add(userInfo);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//關閉
DBUtil.close(rs, statement, connection);
}
return list;
}
}
DBUtil.java
//DBUtil.java
package util;
import java.sql.*;
public class DBUtil {
/***
*本文使用的數據庫名稱爲user,賬號密碼均爲root,
*數據庫含表userinfo,
*該表有三個字段,id(INT),userinfo(VARCHAR),password(VARCHAR)
*讀者可根據數據庫的實際情況對語句進行修改
***/
public static Connection getConnection(){
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/user?useSSL=true&characterEncoding=utf-8&user=root&password=root");
// System.out.println("創建連接成功");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public static void close(ResultSet rs,Statement statement,Connection connection){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement!=null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Main.java
//Main.java
import bean.UserInfo;
import dao.UserInfoDao;
public class Main {
public static void main(String[] args) {
//查找全部
System.out.println("查找全部");
System.out.println(new UserInfoDao().findAll());
//增加
System.out.println("增加");
new UserInfoDao().add(new UserInfo(10,"王五","王五的密碼"));
System.out.println(new UserInfoDao().findAll());
//更新
System.out.println("更新");
new UserInfoDao().update(new UserInfo(10,"張三","張三的密碼"));
System.out.println(new UserInfoDao().findAll());
//按照用戶名查找
System.out.println("按照用戶名查找");
System.out.println(new UserInfoDao().selectFromUsername("張三"));
//按照ID進行刪除
System.out.println("按照ID刪除");
new UserInfoDao().deleteFromUsername("張三");
System.out.println(new UserInfoDao().findAll());
}
}