共計(jì) 1052 個(gè)字符,預(yù)計(jì)需要花費(fèi) 3 分鐘才能閱讀完成。
在 Java 中,可以使用 JDBC(Java Database Connectivity)來讀取數(shù)據(jù)庫(kù)數(shù)據(jù)。以下是一個(gè)簡(jiǎn)單的示例代碼,演示如何連接到數(shù)據(jù)庫(kù),執(zhí)行查詢語句并讀取結(jié)果集中的數(shù)據(jù):
import java.sql.*;
public class ReadDataFromDatabase {public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 連接到數(shù)據(jù)庫(kù)
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
// 創(chuàng)建 Statement 對(duì)象
stmt = conn.createStatement();
// 執(zhí)行查詢語句
rs = stmt.executeQuery("SELECT * FROM mytable");
// 遍歷結(jié)果集并讀取數(shù)據(jù)
while (rs.next()) {int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
// 打印數(shù)據(jù)
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
}
} catch (SQLException e) {e.printStackTrace();
} finally {
try {
// 關(guān)閉 ResultSet
if (rs != null) {rs.close();
}
// 關(guān)閉 Statement
if (stmt != null) {stmt.close();
}
// 關(guān)閉 Connection
if (conn != null) {conn.close();
}
} catch (SQLException e) {e.printStackTrace();
}
}
}
}
在這個(gè)示例代碼中,我們首先通過 DriverManager.getConnection()
方法建立與數(shù)據(jù)庫(kù)的連接,然后創(chuàng)建一個(gè) Statement
對(duì)象來執(zhí)行查詢語句,將查詢結(jié)果存儲(chǔ)在 ResultSet
對(duì)象中。接著通過 rs.next()
方法來遍歷結(jié)果集,使用 rs.getInt()
和rs.getString()
等方法來讀取數(shù)據(jù)。最后,記得在最終關(guān)閉連接、Statement 和 ResultSet 對(duì)象時(shí)使用 close()
方法。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完