package com.simple.util.config.database;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* @program: simple_tools
* @description: 数据库工具类
* @author: ChenWenLong
* @create: 2019-12-31 10:29
**/
public class DataBaseUtils {
/**
* 功能描述:
* 〈获取数据库连接〉
*
* @params : [db]
* @return : java.sql.Connection
* @author : cwl
* @date : 2019/12/31 10:31
*/
public static Connection getConnection(DataBase db) throws Exception {
Properties props = new Properties();
props.put("remarksReporting","true");//获取数据库的备注信息
props.put("user",db.getUserName());
props.put("password",db.getPassWord());
Class.forName(db.getDriver());//注册驱动
return DriverManager.getConnection(db.getUrl(),props);
}
/**
* 功能描述:
* 〈获取数据库列表〉
*
* @params : [db]
* @return : java.util.List<java.lang.String>
* @author : cwl
* @date : 2019/12/31 10:31
*/
public static List<String> getSchemas(DataBase db) throws Exception {
//1.获取元数据
Connection connection = getConnection(db);
DatabaseMetaData metaData = connection.getMetaData();
//2.获取所有数据库列表
ResultSet rs = metaData.getCatalogs();
List<String> list = new ArrayList<>();
while (rs.next()) {
list.add(rs.getString(1));
}
rs.close();
connection.close();
return list;
}
// 数据库内部类
public static class DataBase {
//127.0.0.1:3306/cwl
private static final String mysqlUrl = "jdbc:mysql://[ip]:[port]/[db]?useUnicode=true&characterEncoding=UTF8";
private static final String oracleUrl = "jdbc:oracle:thin:@[ip]:[port]:[db]";
private String dbType;//数据库类型
private String userName;
private String passWord;
private String driver;
private String url;
public DataBase() {}
public DataBase(String dbType) {
this(dbType,"127.0.0.1","3306","");
}
public DataBase(String dbType,String db) {
this(dbType,"127.0.0.1","3306",db);
}
/**
*
* @param dbType 数据库类型
* @param ip ip
* @param port 3306
* @param db cwl
*/
public DataBase(String dbType,String ip,String port,String db) {
this.dbType = dbType;
if("MYSQL".endsWith(dbType.toUpperCase())) {
this.driver="com.mysql.jdbc.Driver";
this.url=mysqlUrl.replace("[ip]",ip).replace("[port]",port).replace("[db]",db);
}else{
this.driver="oracle.jdbc.driver.OracleDriver";
this.url=oracleUrl.replace("[ip]",ip).replace("[port]",port).replace("[db]",db);
}
}
public String getDbType() {
return dbType;
}
public void setDbType(String dbType) {
this.dbType = dbType;
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
}