在Java中,我們可以很方便地通過JDBC連接到MySQL數(shù)據(jù)庫(kù),并實(shí)現(xiàn)數(shù)據(jù)的查詢。以下是一個(gè)基本的Java代碼示例:
import java.sql.*; public class MySQLDemo { static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost:3306/mydatabase"; static final String USER = "username"; static final String PASS = "password"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try { Class.forName(JDBC_DRIVER); System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql = "SELECT id, name, age FROM students"; ResultSet rs = stmt.executeQuery(sql); while(rs.next()){ int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); System.out.print("ID: " + id); System.out.print(", Name: " + name); System.out.println(", Age: " + age); } rs.close(); stmt.close(); conn.close(); } catch (SQLException se) { se.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (stmt != null) stmt.close(); } catch (SQLException se2) { } try { if (conn != null) conn.close(); } catch (SQLException se) { se.printStackTrace(); } } System.out.println("Goodbye!"); } }
在這個(gè)示例中,我們首先定義了JDBC驅(qū)動(dòng),數(shù)據(jù)庫(kù)連接URL,用戶名和密碼。然后我們創(chuàng)建了一個(gè)連接對(duì)象,并使用它來創(chuàng)建一個(gè)Statement對(duì)象。我們所要執(zhí)行的SQL查詢語句是"SELECT id, name, age FROM students",返回一些學(xué)生記錄的id,姓名和年齡。
我們通過stmt.executeQuery()方法執(zhí)行查詢,并將結(jié)果保存在ResultSet對(duì)象rs中。然后我們使用rs.next()迭代數(shù)據(jù)集并提取每個(gè)學(xué)生記錄的id,name和age。在本示例中,我們只是簡(jiǎn)單地將這些值打印在控制臺(tái)上。
最后,我們關(guān)閉ResultSet、Statement和Connection對(duì)象。