生活随笔
收集整理的這篇文章主要介紹了
JDBC使用详解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
引言
JDBC(Java DataBase Connectivity)是Java連接數據庫的的方法;其實本質就是SUN公司定制的一套接口,這樣就可以實現Java和各種不同數據庫間的連接,如下圖:
注:本文使用IDEA示范,數據庫使用的是MySQL數據庫;
IDEA導入數據庫連接Jar包步驟
首先我們要先有對應的MySQL數據庫連接驅動jar包,沒有的可以評論區找我要;
正常創建一個IDEA項目,如圖:
接下來就按圖操作導入jar包;
這樣我就創建了一個名為lib的文件夾,然后把 mysql-connector-java-8.0.16.jar 粘貼到lib目錄下;
如圖:
最后一步把jar包導入到項目中,即右鍵該jar包,再點擊Add as Library;
這樣就導入jar包了;
接下來就是JDBC的基本操作;
JDBC編程操作
JDBC在Java代碼中可以總結為五個操作步驟:
注冊驅動(確定連接的數據庫)獲取連接(打開JVM進程和數據庫進程之間的通道)獲取數據庫操作對象(可以用來執行sql語句)執行SQL語句(如果是select查詢語句那么需要處理查詢結果)釋放資源(關閉第二步開啟的進程通道)
我自己先創建了一個test02數據庫,其中一個表為t_user,如圖:
下面就來展示一下使用JDBC實現連接數據庫的登錄操作(存在問題):
package jdbctest01;import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class JdbcTest01 {public static void main(String[] args
) {Map<String, String> userLoginInfo
= initUI();boolean loginSuccess
= login(userLoginInfo
);System.out
.println(loginSuccess
? "登錄成功" : "登錄失敗");}private static boolean login(Map<String, String> userLoginInfo
) {boolean loginSuccess
= false; String loginName
= userLoginInfo
.get("loginName"); String password
= userLoginInfo
.get("password"); Connection connection
= null;Statement statement
= null;ResultSet resultSet
= null;try {Class.forName("com.mysql.cj.jdbc.Driver");connection
= DriverManager.getConnection("jdbc:mysql://localhost:3306/test02?serverTimezone=UTC", "root", "020216");statement
= connection
.createStatement();String sql
= "select * from t_user where loginName = '"+ loginName
+"' and loginPwd = '"+ password
+"'";resultSet
= statement
.executeQuery(sql
);if (resultSet
.next()) {loginSuccess
= true;}} catch (ClassNotFoundException | SQLException e
) {e
.printStackTrace();} finally {if (resultSet
!= null) {try {resultSet
.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();}}}return loginSuccess
;}private static Map<String, String> initUI() {Scanner scan
= new Scanner(System.in
);System.out
.print("用戶名:");String userName
= scan
.nextLine();System.out
.print("密碼:");String password
= scan
.nextLine();Map<String, String> userLoginInfo
= new HashMap<>();userLoginInfo
.put("loginName", userName
);userLoginInfo
.put("password", password
);return userLoginInfo
;}
}
這樣就實現了一個登錄功能
但是這樣存在SQL注入問題,SQL注入可以自己搜集資料了解一下,簡而言之就是不安全,我示范一下:
可以看到,張三密碼是200002,但是我卻可以通過SQL注入語句1' or '1'='1登錄成功,這樣就存在著很大的問題;
為了解決SQL注入問題,可以使用如下方法:
代碼如下:
package jdbctest01;import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class JdbcTest02 {public static void main(String[] args
) {Map<String, String> userLoginInfo
= initUI();boolean loginSuccess
= login(userLoginInfo
);System.out
.println(loginSuccess
? "登錄成功" : "登錄失敗");}private static boolean login(Map<String, String> userLoginInfo
) {boolean loginSuccess
= false;String userName
= userLoginInfo
.get("userName");String password
= userLoginInfo
.get("password");Connection connection
= null;PreparedStatement preparedStatement
= null;ResultSet resultSet
= null;try {Class.forName("com.mysql.cj.jdbc.Driver");connection
= DriverManager.getConnection("jdbc:mysql://localhost:3306/test02?serverTimezone=UTC", "root", "020216");String sql
= "select * from t_user where loginName = ? and loginPwd = ?";preparedStatement
= connection
.prepareStatement(sql
);preparedStatement
.setString(1, userName
); preparedStatement
.setString(2, password
); resultSet
= preparedStatement
.executeQuery();if (resultSet
.next()) {loginSuccess
= true;}} catch (ClassNotFoundException | SQLException e
) {e
.printStackTrace();} finally {if (resultSet
!= null) {try {resultSet
.close();} catch (SQLException e
) {e
.printStackTrace();}}if (preparedStatement
!= null) {try {preparedStatement
.close();} catch (SQLException e
) {e
.printStackTrace();}}if (connection
!= null) {try {connection
.close();} catch (SQLException e
) {e
.printStackTrace();}}}return loginSuccess
;}private static Map<String, String> initUI() {Scanner scan
= new Scanner(System.in
);System.out
.print("請輸入用戶名:");String userName
= scan
.nextLine();System.out
.print("請輸入密碼:");String password
= scan
.nextLine();Map<String, String> userLoginInfo
= new HashMap<>();userLoginInfo
.put("userName" , userName
);userLoginInfo
.put("password", password
);return userLoginInfo
;}
}
SQL注入失敗:
可以發現主要區別是獲取數據庫操作對象時不再使用Statement,而使用PreparedStatement,這樣就可以解決SQL注入問題;所以實際情況下,使用PreparedStatement會更多,還有占位符操作,也很簡單,代碼中有注釋,自己嘗試一下就明白了;代碼可以多看幾遍找找區別;
這就是JDBC最基礎的操作,其實就是這幾個固定步驟,實在不理解先記住就行了,之后用多了就會明白了;
接下來我們將JDBC的一些操作進行封裝;
自定義JDBC工具類
在這里我們將注冊、連接、關閉操作封裝起來,構成一個工具類;
代碼有詳細注釋;
package jdbctest01.mytest;import java.sql.*;
public class DBUtil {private DBUtil(){}static {try {Class.forName("com.mysql.cj.jdbc.Driver");} catch (ClassNotFoundException e
) {e
.printStackTrace();}}public static Connection getConnection() throws SQLException {return DriverManager.getConnection("jdbc:mysql://localhost:3306/test02?serverTimezone=UTC", "root", "020216");}public static void close(Connection connection
, Statement statement
, ResultSet resultSet
) {if (resultSet
!= null) {try {resultSet
.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();}}}
}
這個操作也可以自己實現一下,并不難;
這里值得一提的就是注冊驅動放到了靜態代碼塊中,這樣就在保證調用的同時避免重復調用;
CRUD操作
對于數據庫的操作其實最常用的還是增刪改查,但是每次都重寫代碼實在是復雜,所以這里同樣可以自己封裝一個增刪改查操作;這里還是使用之前的test02數據庫,這里是對bank表進行的操作;bank表如圖:
接下來是我自己封裝的一個增刪改查操作代碼(這里使用了DBUtil工具類):
package jdbctest01.mytest;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
public class CRUD
{public static int add(int num
, String user
, int money
) throws SQLException {Connection connection
= null;PreparedStatement preparedStatement
= null;connection
= DBUtil.getConnection();String sql
= "insert into bank(num, user, money)values(?, ?, ?)";preparedStatement
= connection
.prepareStatement(sql
);preparedStatement
.setInt(1, num
); preparedStatement
.setString(2, user
); preparedStatement
.setInt(3, money
); int count
= preparedStatement
.executeUpdate(); DBUtil.close(connection
, preparedStatement
, null);return count
;}public static int delete(int num
) throws SQLException {Connection connection
= null;PreparedStatement preparedStatement
= null;connection
= DBUtil.getConnection();String sql
= "delete from bank where num = ?";preparedStatement
= connection
.prepareStatement(sql
);preparedStatement
.setInt(1, num
);int count
= preparedStatement
.executeUpdate(); DBUtil.close(connection
, preparedStatement
, null);return count
;}public static int update(int num
, String user
, int money
) throws SQLException {Connection connection
= null;PreparedStatement preparedStatement
= null;connection
= DBUtil.getConnection();String sql
= "update bank set user = ?, money = ? where num = ?";preparedStatement
= connection
.prepareStatement(sql
);preparedStatement
.setString(1, user
);preparedStatement
.setInt(2, money
);preparedStatement
.setInt(3, num
);int count
= preparedStatement
.executeUpdate(); DBUtil.close(connection
, preparedStatement
, null);return count
;}@Deprecatedpublic static ResultSet select(int num
) throws SQLException {Connection connection
= null;PreparedStatement preparedStatement
= null;ResultSet resultSet
= null;connection
= DBUtil.getConnection();String sql
= "select * from bank where num = ?";preparedStatement
= connection
.prepareStatement(sql
);preparedStatement
.setInt(1, num
);resultSet
= preparedStatement
.executeQuery(); if (resultSet
.next()) {System.out
.println("num:" + resultSet
.getInt("num") +" user:" + resultSet
.getString("user") + " money:" + resultSet
.getInt("money"));}DBUtil.close(connection
, preparedStatement
, resultSet
);return resultSet
;}public static Bank selectElem(int num
) throws SQLException {Connection connection
= null;PreparedStatement preparedStatement
= null;ResultSet resultSet
= null;Bank bank
= new Bank();connection
= DBUtil.getConnection();String sql
= "select * from bank where num = ?";preparedStatement
= connection
.prepareStatement(sql
);preparedStatement
.setInt(1, num
);resultSet
= preparedStatement
.executeQuery(); if (resultSet
.next()) {bank
.setNum(resultSet
.getInt("num"));bank
.setUser(resultSet
.getString("user"));bank
.setMoney(resultSet
.getInt("money"));}DBUtil.close(connection
, preparedStatement
, resultSet
);return bank
;}
}
這里也要注意到一點:當執行select查詢語句時,使用的是executeQuery()方法,而增刪改都是使用的executeUpdate()方法;
總結
JDBC其實并沒有多少東西,其實總的就是那幾步操作,可能剛一接觸會有點懵,習慣就好了;
這里還是想提一下:代碼只是參考,我希望你可以通過我的代碼了解到操作方法,可以自己去創建一個數據庫嘗試;
當然有問題或者想要相關資源評論區可以留言,希望這篇文章可以給你帶來幫助!!!
歡迎大家的點評!
總結
以上是生活随笔為你收集整理的JDBC使用详解的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。