您好,登錄后才能下訂單哦!
今天小編給大家分享一下怎么使用JDBC連接數據庫并執行SQL語句的相關知識點,內容詳細,邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。
JDBC(Java Database Connectivity)是Java程序與數據庫進行交互的一種標準接口,它提供了一種簡單的方式來連接和操作數據庫。在使用JDBC之前,需要先了解以下幾個概念:
JDBC Driver:JDBC驅動程序是一個Java類,用于將Java應用程序與特定數據庫管理系統(DBMS)連接。JDBC驅動程序分為四種類型:JDBC-ODBC橋接驅動程序、本地API驅動程序、網絡協議驅動程序和本地協議驅動程序。
Connection:Connection是一個JDBC接口,用于連接到數據庫。在Java程序中,通過Connection接口的實現類來實現與數據庫的連接。
Statement:Statement是一個JDBC接口,用于向數據庫發送SQL語句并執行它們。在Java程序中,通過Connection對象創建Statement對象。
ResultSet:ResultSet是一個JDBC接口,用于表示從數據庫中檢索到的結果集。ResultSet對象通過Statement對象的executeQuery()方法返回。
下面是一個簡單的JDBC連接示例:
import java.sql.*; public class JDBCDemo { public static void main(String[] args) { try { // 加載JDBC驅動程序 Class.forName("com.mysql.cj.jdbc.Driver"); // 建立數據庫連接 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "password"); // 執行SQL查詢 Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM users"); while (rs.next()) { System.out.println(rs.getInt(1) + ", " + rs.getString(2) + ", " + rs.getString(3)); } // 關閉數據庫連接 rs.close(); stmt.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } } }
在實際開發中,我們通常會抽取出一個JDBC工具類來封裝JDBC相關操作,以方便代碼的重用和維護。下面是一個簡單的JDBC工具類示例:
import java.sql.*; public class JDBCUtils { private static final String URL = "jdbc:mysql://localhost:3306/mydb"; private static final String USER = "root"; private static final String PASSWORD = "password"; static { try { // 加載JDBC驅動程序 Class.forName("com.mysql.cj.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Connection getConnection() { Connection conn = null; try { // 建立數據庫連接 conn = DriverManager.getConnection(URL, USER, PASSWORD); } catch (SQLException e) { e.printStackTrace(); } return conn; } public static void release(ResultSet rs, Statement stmt, Connection conn) { try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
Statement是JDBC中最基本的操作方式,它用于向數據庫發送SQL語句并執行它們。下面是一個使用Statement進行CRUD操作的示例:
import java.sql.*; public class StatementCRUD { public static void main(String[] args) { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = JDBCUtils.getConnection(); stmt = conn.createStatement(); // 插入數據 String sql = "INSERT INTO users (name, age) VALUES ('Tom', 18)"; stmt.executeUpdate(sql); // 更新數據 sql = "UPDATE users SET age = 20 WHERE name = 'Tom'"; stmt.executeUpdate(sql); // 刪除數據 sql = "DELETE FROM users WHERE age = 20"; stmt.executeUpdate(sql); // 查詢數據 sql = "SELECT * FROM users"; rs = stmt.executeQuery(sql); while (rs.next()) { System.out.println(rs.getInt(1) + ", " + rs.getString(2) + ", " + rs.getInt(3)); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCUtils.release(rs, stmt, conn); } } }
下面是一個使用PreparedStatement進行CRUD操作的示例:
import java.sql.*; public class PreparedStatementCRUD { public static void main(String[] args) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = JDBCUtils.getConnection(); // 插入數據 String sql = "INSERT INTO users (name, age) VALUES (?, ?)"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, "Tom"); pstmt.setInt(2, 18); pstmt.executeUpdate(); // 更新數據 sql = "UPDATE users SET age = ? WHERE name = ?"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, 20); pstmt.setString(2, "Tom"); pstmt.executeUpdate(); // 刪除數據 sql = "DELETE FROM users WHERE age = ?"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, 20); pstmt.executeUpdate(); // 查詢數據 sql = "SELECT * FROM users"; pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); while (rs.next()) { System.out.println(rs.getInt(1) + ", " + rs.getString(2) + ", " + rs.getInt(3)); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCUtils.release(rs, pstmt, conn); } } }
Dao(Data Access Object)模式是一種用于封裝數據訪問邏輯的設計模式。它將數據訪問邏輯與業務邏輯分離開來,使得代碼更易于維護和擴展。下面是一個使用Dao模式進行CRUD操作的示例:
import java.sql.*; public class UserDAO { private static final String INSERT_SQL = "INSERT INTO users (name, age) VALUES (?, ?)"; private static final String UPDATE_SQL = "UPDATE users SET age = ? WHERE name = ?"; private static final String DELETE_SQL = "DELETE FROM users WHERE age = ?"; private static final String SELECT_SQL = "SELECT * FROM users"; public void insert(User user) { Connection conn = null; PreparedStatement pstmt = null; try { conn = JDBCUtils.getConnection(); pstmt = conn.prepareStatement(INSERT_SQL); pstmt.setString(1, user.getName()); pstmt.setInt(2, user.getAge()); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { JDBCUtils.release(null, pstmt, conn); } } public void update(User user) { Connection conn = null; PreparedStatement pstmt = null; try { conn = JDBCUtils.getConnection(); pstmt = conn.prepareStatement(UPDATE_SQL); pstmt.setInt(1, user.getAge()); pstmt.setString(2, user.getName()); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { JDBCUtils.release(null, pstmt, conn); } } public void delete(int age) { Connection conn = null; PreparedStatement pstmt = null; try { conn = JDBCUtils.getConnection(); pstmt = conn.prepareStatement(DELETE_SQL); pstmt.setInt(1, age); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { JDBCUtils.release(null, pstmt, conn); } } public List<User> selectAll() { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; List<User> userList = new ArrayList<>(); try { conn = JDBCUtils.getConnection(); pstmt = conn.prepareStatement(SELECT_SQL); rs = pstmt.executeQuery(); while (rs.next()) { User user = new User(); user.setId(rs.getInt(1)); user.setName(rs.getString(2)); user.setAge(rs.getInt(3)); userList.add(user); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCUtils.release(rs, pstmt, conn); } return userList; } } public class User { private int id; private String name; private int age; // 省略getter、setter方法 }
PreparedStatement是一種預編譯的Statement,它可以通過占位符的方式來替換SQL語句中的參數,避免了SQL注入的危險。下面是一個使用PreparedStatement進行CRUD操作的示例:
import java.sql.*; public class PrepareStatementCRUD { public static void main(String[] args) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = JDBCUtils.getConnection(); // 插入數據 String sql = "INSERT INTO users (name, age) VALUES (?, ?)"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, "Tom"); pstmt.setInt(2, 18); pstmt.executeUpdate(); // 更新數據 sql = "UPDATE users SET age = ? WHERE name = ?"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, 20); pstmt.setString(2, "Tom"); pstmt.executeUpdate(); // 刪除數據 sql = "DELETE FROM users WHERE age = ?"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, 20); pstmt.executeUpdate(); // 查詢數據 sql = "SELECT * FROM users"; pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); while (rs.next()) { System.out.println(rs.getInt(1) + ", " + rs.getString(2) + ", " + rs.getInt(3)); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCUtils.release(rs, pstmt, conn); } } }
以上就是“怎么使用JDBC連接數據庫并執行SQL語句”這篇文章的所有內容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會為大家更新不同的知識,如果還想學習更多的知識,請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。