溫馨提示×

java怎么讀取數(shù)據(jù)庫數(shù)據(jù)

小億
162
2024-03-18 13:45:52
欄目: 編程語言

在Java中讀取數(shù)據(jù)庫數(shù)據(jù)通常需要使用JDBC(Java Database Connectivity)來連接數(shù)據(jù)庫,并執(zhí)行SQL語句來查詢數(shù)據(jù)。以下是一個(gè)簡單的示例代碼來讀取數(shù)據(jù)庫數(shù)據(jù):

```java

import java.sql.*;

public class ReadDataFromDatabase {

public static void main(String[] args) {

String url = "jdbc:mysql://localhost:3306/mydatabase";

String username = "root";

String password = "password";

try {

Connection conn = DriverManager.getConnection(url, username, password);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");

while (rs.next()) {

int id = rs.getInt("id");

String name = rs.getString("name");

double price = rs.getDouble("price");

System.out.println("ID: " + id + ", Name: " + name + ", Price: " + price);

}

rs.close();

stmt.close();

conn.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

```

在上面的代碼中,首先通過`DriverManager.getConnection()`方法來建立與數(shù)據(jù)庫的連接,然后創(chuàng)建一個(gè)`Statement`對象來執(zhí)行SQL查詢語句,接著通過`ResultSet`對象來遍歷查詢結(jié)果并讀取數(shù)據(jù)。最后記得關(guān)閉所有的資源,包括`ResultSet`、`Statement`和`Connection`。

0