/** * Copyright (c) 2020 佳缘科技 All rights reserved. *
* https://www.scjydz.com *
* 版权所有,侵权必究!
*/
package com.wjp.modules.devtools.utils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.wjp.modules.devtools.config.DataSourceInfo;
import com.wjp.modules.devtools.config.query.AbstractQuery;
import com.wjp.modules.devtools.entity.TableFieldEntity;
import com.wjp.modules.devtools.entity.TableInfoEntity;
import lombok.extern.slf4j.Slf4j;
import oracle.jdbc.OracleConnection;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* DB工具类
*
* @author Toby javatangbin@163.com
*/
@Slf4j
public class DbUtils {
private static final int CONNECTION_TIMEOUTS_SECONDS = 6;
/**
* 获得数据库连接
*
* @param info
* @return
* @throws ClassNotFoundException
* @throws SQLException
*/
public static Connection getConnection(DataSourceInfo info) throws ClassNotFoundException, SQLException {
DriverManager.setLoginTimeout(CONNECTION_TIMEOUTS_SECONDS);
Class.forName(info.getDbType().getDriverClass());
Connection connection = DriverManager.getConnection(info.getConnUrl(), info.getUsername(), info.getPassword());
if(info.getDbType() == DbType.Oracle){
((OracleConnection)connection).setRemarksReporting(true);
}
return connection;
}
/**
* 获取数据库表信息
*/
public static TableInfoEntity getTablesInfo(DataSourceInfo info, String tableName) {
try {
AbstractQuery dbQuery = info.getDbQuery();
//查询数据
PreparedStatement preparedStatement = info.getConnection().prepareStatement(dbQuery.tablesSql(tableName));
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
TableInfoEntity tableInfo = new TableInfoEntity();
tableInfo.setTableName(rs.getString(dbQuery.tableName()));
tableInfo.setClassName(GenUtils.columnToJava(tableInfo.getTableName()));
tableInfo.setTableComment(rs.getString(dbQuery.tableComment()));
tableInfo.setDatasourceId(info.getId());
return tableInfo;
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
/**
* 获取所有的数据库表
*/
public static List