Java Database Connectivity (JDBC) 是一種用于在Java中執(zhí)行SQL語(yǔ)句的API,通過(guò)JDBC可以很方便地連接各種不同的數(shù)據(jù)庫(kù),包括MySQL數(shù)據(jù)庫(kù)。下面是一個(gè)使用JDBC鏈接MySQL數(shù)據(jù)庫(kù)的示例:
import java.sql.*; public class MySQLConnector { private static final String URL = "jdbc:mysql://localhost:3306/test"; private static final String USERNAME = "root"; private static final String PASSWORD = "123456"; public static void main(String[] args) { Connection conn = null; try { // 注冊(cè)JDBC驅(qū)動(dòng) Class.forName("com.mysql.cj.jdbc.Driver"); // 獲取數(shù)據(jù)庫(kù)連接 conn = DriverManager.getConnection(URL, USERNAME, PASSWORD); // 執(zhí)行SQL語(yǔ)句 String sql = "SELECT * FROM student"; Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql); // 處理查詢結(jié)果 while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); System.out.println("Id: " + id + ", Name: " + name + ", Age: " + age); } // 關(guān)閉數(shù)據(jù)庫(kù)連接 rs.close(); stmt.close(); conn.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
在這個(gè)示例中,我們首先定義了連接MySQL數(shù)據(jù)庫(kù)所需要的URL、用戶名和密碼,然后使用JDBC API注冊(cè)了MySQL的JDBC驅(qū)動(dòng),通過(guò)DriverManager.getConnection()方法獲取數(shù)據(jù)庫(kù)連接,執(zhí)行SQL語(yǔ)句查詢數(shù)據(jù)庫(kù)中的數(shù)據(jù),并將結(jié)果打印出來(lái)。最后,我們關(guān)閉了數(shù)據(jù)庫(kù)連接和ResultSet和Statement對(duì)象。