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 DataBaseUtil {
// private static Log logger = LogFactory.getLog(DataBaseUtil.class);
/**
* 读取配置文件获取连接数据库的数据库名
*
* @return String 数据库名
*/
public static String getDatabaseName() {
String databaseName = PropertiesLoader.getPropertiesVal("url");
return databaseName;
}
/**
* 读取配置文件获取连接数据库的用户名
*
* @return String 用户名
*/
public static String getUserOfDatabase() {
String user = PropertiesLoader.getPropertiesVal("userName");
return user;
}
/**
* 获取指定数据库和用户的所有表名
*
* @param conn 连接数据库对象
* @param user 用户
* @param database 数据库名
* @return
* @throws Exception
*/
public static List<String> getAllTableNames(Connection conn, String user, String database) throws Exception {
List<String> tableNames = new ArrayList<String>();
ResultSet rest = null;
if (conn != null) {
try {
DatabaseMetaData dbmd = conn.getMetaData();
// 表名列表
rest = dbmd.getTables(database, null, null, new String[] { "TABLE" });
// 输出 table_name
while (rest.next()) {
String tableSchem = rest.getString("TABLE_SCHEM");
if (user.equalsIgnoreCase(tableSchem)) {
tableNames.add(rest.getString("TABLE_NAME"));
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (null != rest) {
rest.close();
}
if (null != conn) {
conn.close();
}
}
}
return tableNames;
}
public static void main(String[] args) {
try {
Connection connection = null;
String url = PropertiesLoader.getPropertiesVal("url");
String userName = PropertiesLoader.getPropertiesVal("userName");
String passWord = PropertiesLoader.getPropertiesVal("passWord");
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection(url, userName, passWord);
connection.setAutoCommit(false);
System.out.println("connect database is ok!");
try {
List<String> tables = getAllTableNames(connection, getUserOfDatabase(), getDatabaseName());
System.out.println(tables.size());
} catch (Exception e) {
e.printStackTrace();
}
} catch (SQLException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertiesLoader {
static Properties props = new Properties();
static {
try {
InputStream in;
try {
in = Class.forName(PropertiesLoader.class.getName()).getResourceAsStream("/config/config.properties");
props.load(in);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getPropertiesVal(String key) {
return props.getProperty(key);
}
public static void main(String[] args) throws ClassNotFoundException {
System.out.println(PropertiesLoader.getPropertiesVal("data_path"));
}
}
config.property:
url=jdbc:oracle:thin:@ip:1521:orcl
userName=
passWord=