在Java中從數(shù)據(jù)庫中取數(shù)據(jù)可以使用JDBC(Java Database Connectivity)技術(shù),以下是一個簡單的示例代碼:
import java.sql.*;public class DatabaseApp {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 連接數(shù)據(jù)庫
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase",
"username", "password");
// 創(chuàng)建Statement對象
stmt = conn.createStatement();
// 執(zhí)行查詢語句
String sql = "SELECT * FROM mytable";
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);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 關(guān)閉數(shù)據(jù)庫連接
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
上述代碼首先通過`DriverManager.getConnection`方法建立與數(shù)據(jù)庫的連接,然后創(chuàng)建`Statement`對象用于執(zhí)行SQL語句。執(zhí)行查詢語句可以使用`executeQuery`方法,并通過`ResultSet`對象獲取查詢結(jié)果。最后在`while`循環(huán)中提取每一行的數(shù)據(jù)并進行處理。
需要注意的是,在使用完數(shù)據(jù)庫連接、Statement對象和ResultSet對象后,需要調(diào)用`close`方法關(guān)閉它們,以釋放資源和避免內(nèi)存泄漏。