Java表格读取MySQL
时间: 2023-07-22 15:37:46 浏览: 48
要在Java中读取MySQL数据库中的表格,可以使用JDBC API和MySQL Connector/J驱动程序。以下是一个基本的示例代码,可以读取MySQL数据库中的表格并将其显示在Java控制台中:
```java
import java.sql.*;
public class ReadMySQLTable {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Load the MySQL Connector/J driver
Class.forName("com.mysql.jdbc.Driver");
// Connect to the database
conn = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase", "username", "password");
// Create a statement
stmt = conn.createStatement();
// Execute a query
rs = stmt.executeQuery("SELECT * FROM mytable");
// Display the results
while (rs.next()) {
System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name") + ", Age: " + rs.getInt("age"));
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
// Clean up resources
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
请注意,此示例假定您已经安装了MySQL数据库,并且已经创建了一个名为"mydatabase"的数据库和一个名为"mytable"的表格。同时,您需要将"username"和"password"替换为您的MySQL用户名和密码。