帮我编写一个mysql使用jdbc获取当前库所有表名的工具类
时间: 2024-02-06 21:09:37 浏览: 121
java连接数据库的JDBC.rar_jdbc mysql
好的,下面是一个获取当前库所有表名的工具类代码示例:
```
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class MysqlJdbcUtil {
// 数据库连接配置
private static final String URL = "jdbc:mysql://localhost:3306/test";
private static final String USERNAME = "root";
private static final String PASSWORD = "123456";
// 获取数据库连接
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USERNAME, PASSWORD);
}
// 获取当前库所有表名
public static List<String> getTableNames() throws SQLException {
List<String> tableNames = new ArrayList<>();
Connection conn = null;
ResultSet rs = null;
try {
conn = getConnection();
DatabaseMetaData metaData = conn.getMetaData();
rs = metaData.getTables(null, null, null, new String[] { "TABLE" });
while (rs.next()) {
tableNames.add(rs.getString("TABLE_NAME"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (rs != null) {
rs.close();
}
if (conn != null) {
conn.close();
}
}
return tableNames;
}
}
```
使用方法:
```
try {
List<String> tableNames = MysqlJdbcUtil.getTableNames();
System.out.println(tableNames);
} catch (SQLException e) {
e.printStackTrace();
}
```
阅读全文