如何返回正在连接的数据库的名字
发布网友
发布时间:2022-05-26 15:09
我来回答
共1个回答
热心网友
时间:2023-10-23 14:33
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.loushang.persistent.jdbc.datasource.PropertyDataSourceFactoryImpl;
public class DataBaseUtil {
private static Log logger = LogFactory.getLog(DataBaseUtil.class);
public static final String DATASOURCE_FILENAME = "datasource.properties"; //连接数据库的数据源文件
public static final String DATASOURCE_URL = "dataSource.url"; //数据源文件里url的key
public static final String DATASOURCE_USERNAME = "dataSource.username"; //数据源文件里用户名的key
/**
* 读取配置文件信息
* @return Properties 配置文件信息
*/
public static Properties getProperties() {
//InputStream in = ClassLoader.getSystemResourceAsStream(DATASOURCE_FILENAME);
InputStream in = PropertyDataSourceFactoryImpl.class.getClassLoader()
.getResourceAsStream(DATASOURCE_FILENAME);
if (in == null) {
in = Thread.currentThread().getContextClassLoader().getResourceAsStream(DATASOURCE_FILENAME);
if(in == null){
logger.warn("Can not find the datasource config file 'datasource.properties'.");
}
}
Properties properties = new Properties();
try {
properties.load(in);
} catch (IOException e) {
logger.error("Error occurred when loading datasource config file.", e);
}
return properties;
}
/**
* 读取配置文件获取连接数据库的数据库名
* @return String 数据库名
*/
public static String getDatabaseName() {
String databaseName = "";
Properties p = getProperties();
String database = p.getProperty(DATASOURCE_URL);
int startIndex = database.lastIndexOf(":");
databaseName = database.substring(startIndex+1, database.length());
return databaseName;
}