java如何讀取數(shù)據(jù)庫(kù)數(shù)據(jù)

小億
135
2024-04-24 11:03:07

在Java中,可以使用JDBC(Java Database Connectivity)來讀取數(shù)據(jù)庫(kù)數(shù)據(jù)。以下是一個(gè)簡(jiǎn)單的示例代碼,演示如何連接到數(shù)據(jù)庫(kù),執(zhí)行查詢語(yǔ)句并讀取結(jié)果集中的數(shù)據(jù):

```java

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í)行查詢語(yǔ)句

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í)行查詢語(yǔ)句,將查詢結(jié)果存儲(chǔ)在`ResultSet`對(duì)象中。接著通過`rs.next()`方法來遍歷結(jié)果集,使用`rs.getInt()`和`rs.getString()`等方法來讀取數(shù)據(jù)。最后,記得在最終關(guān)閉連接、Statement和ResultSet對(duì)象時(shí)使用`close()`方法。

0