在Java中讀取數據庫數據通常需要使用JDBC(Java Database Connectivity)來連接數據庫,并執行SQL語句來查詢數據。以下是一個簡單的示例代碼來讀取數據庫數據:
```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()`方法來建立與數據庫的連接,然后創建一個`Statement`對象來執行SQL查詢語句,接著通過`ResultSet`對象來遍歷查詢結果并讀取數據。最后記得關閉所有的資源,包括`ResultSet`、`Statement`和`Connection`。