Java读取数据库列表之和
时间: 2023-11-27 18:50:41 浏览: 34
要读取数据库中的表名列表,你需要使用JDBC API连接到数据库并执行适当的SQL查询。以下是一个简单的Java程序,可以连接到MySQL数据库并读取表名列表:
```java
import java.sql.*;
public class ReadTableNames {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/your_database_name";
static final String USER = "your_mysql_username";
static final String PASS = "your_mysql_password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
String sql = "SHOW TABLES";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
String tableName = rs.getString("Tables_in_your_database_name");
System.out.println(tableName);
}
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}
```
请注意,你需要将`your_database_name`,`your_mysql_username`和`your_mysql_password`替换为你自己的数据库名称、用户名和密码。此外,你需要将JDBC驱动程序的类路径指向正确的位置。
该程序使用`SHOW TABLES` SQL查询从数据库中读取表名列表,并将结果集中的每个表名打印到控制台上。
希望这可以帮助你读取数据库列表。