java mysql jdbc连接数据库

1.获取一个连接

/**
     * 获取数据库连接
     * @author songmin
     * @param generateData:
     * @date 2021/6/12 14:57
     * @return: java.sql.Connection
     */
    public static Connection getConnection(GenerateData generateData){
        String url = generateData.getDbUrl() ;
        String username = generateData.getDbUserName();
        String password = generateData.getDbPassword();
        Connection con = null;
        try{ con = DriverManager.getConnection(url , username , password ) ;
        }catch(SQLException se){
            System.out.println("数据库连接失败!");
            se.printStackTrace() ;
        }
        return con;
    }

2.获取连接之后查询

/**
     * 获取所有表
     * @author songmin
     * @param generateData:
     * @date 2021/6/12 15:07
     * @return: java.lang.String
     */
    public static Set<String> getAllTable(GenerateData generateData){
        Connection conn = getConnection(generateData);
        PreparedStatement pstmt = null;
        String sql = "select table_name from information_schema.tables where table_schema=?";
        Set<String> tableNames = new HashSet<>();
        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,generateData.getDbName());
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()){
                 tableNames.add(rs.getString("TABLE_NAME"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            close(pstmt,conn);
        }
        return tableNames;
    }

 

3.关闭连接的方法

/**
     * 关闭连接
     * @author songmin
     * @param statement:
     * @param conn:
     * @date 2021/6/12 15:08
     * @return: void
     */
    public static void close(Statement statement, Connection conn) {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

 4.功能测试

public static void main(String[] args) {
        GenerateData generateData = new GenerateData();
        generateData.setDbName("generate_code_test");
        generateData.setDbUrl("jdbc:mysql://localhost:3306/generate_code_test?serverTimezone=CTT&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useAffectedRows=true");
        generateData.setDbUserName("root");
        generateData.setDbPassword("123456");
        Set<String> tables = getAllTable(generateData);
        for (String str : tables) {
            logger.info("表名 {}",str);
        }
    }

 

posted @ 2021-06-13 16:43  执笔coding  阅读(45)  评论(0编辑  收藏  举报