Java连接各种数据库操作(mysql、oracle、postgresql、gbase、mongo)

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS PostgreSQL,集群系列 2核4GB
简介: Java连接各种数据库操作(mysql、oracle、postgresql、gbase、mongo)

本篇博客拖延了很久,可能细节处有些许遗忘了

项目需求要支持多种数据库的操作:基本的通过sql进行增删改查、查某个库的所有表、查数据表的字段、表数据及对应类型长度,👇都有实现,涉及到mysql、oracle、postgresql、gbase、mongo五种数据库


一、先上代码


1.pom引入配置


–各位如果需要驱动安装包可以私我,应该gbase的驱动包是最难找的了

      <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>42.5.0</version>
      </dependency>
      <dependency>
        <groupId>com.oracle.database.jdbc</groupId>
        <artifactId>ojdbc8</artifactId>
        <version>21.7.0.0</version>
      </dependency>
      <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>3.0.4</version>
      </dependency>
      <dependency>
        <groupId>gbase-connector-java</groupId>
        <artifactId>gbase-connector-java</artifactId>
        <version>8.3.81.53</version>
      </dependency>


2.demo代码


mysql


main方法

public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        String mysqlQueryTables = "select table_name from information_schema.tables where table_schema='test'";
        String insertToMysql = "insert into `yzh_0922_002` (yzh_0922_002_no,id,sheet_name) values( 4,null,null)";
        String mysqlTableInfo = "select * from information_schema.COLUMNS where table_name = 'aa_wy_test_a' and table_schema = 'test'";
        String mysqlTableRows = "select count(0) from " + "table_name";
        int page = 2;
        int size = 10;
        String q = page == 0 && size == 0 ? "" : " limit " + (page - 1) * size + "," + size;
        String mysqlQuerySql = "select `amount`,`id` from `" + "aa_wy_test_a" + "`" + q;
        try {
//            mysql数据库
            connection = mysqlConnection();
            insertToMysql(connection, insertToMysql);
            getDbTables(connection, mysqlQueryTables);
            getTableColumn(connection, "aa_wy_test_a");
            getTableRowsCount(connection, mysqlTableRows);
            getTableData(connection, mysqlQuerySql);
            //insert
//            String insertSql ="insert into accounts (id,name,age,salary) values( 15,\'0xx\',11,12)";
//            statement = connection.createStatement();
//            statement.executeQuery(insertSql);
            //delete
//            String delSql ="drop table if exists aaaa_missing";
//            statement.executeUpdate(delSql);
            //select
//                String sql1 ="select * from aa_wy_test_a";
//            statement = connection.createStatement();
//            ResultSet resultSet = statement.executeQuery(sql1);
//            while(resultSet.next()) {
//                System.out.println("------------" + resultSet.getString("TABLE_NAME"));
//            }
//            convertList(resultSet);
//            resultSet.close();
//
//            statement.close();
//            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

获取表中数据

    private static List<Map<String, ?>> convertList(ResultSet rs) throws SQLException {
        List<Map<String, ?>>  list = new ArrayList<>();
        while (rs.next()) {
            ResultSetMetaData md = rs.getMetaData();//获取键名
            int columnCount = md.getColumnCount();//获取列的数量
            Map<String, Object> orderedRecords = new LinkedHashMap<>();
            for (int i = 1; i <= columnCount; i++) {
                System.out.println(md.getColumnName(i) + "---" + rs.getObject(i) + ", -------md:" + md.getColumnTypeName(i));
                orderedRecords.put(md.getColumnName(i), rs instanceof BigInteger ? ((BigInteger) rs).longValue() : rs);
            }
            list.add(orderedRecords);
        }
        return list;
    }


其余方法

//获取连接
private static Connection mysqlConnection() throws Exception {
        String mysqlUser = "";
        String mysqlPassword = "";
        String mysqlUrl = "jdbc:mysql://ip:3306/test";
        String driverClassName = "com.mysql.cj.jdbc.Driver";
        Class.forName(driverClassName);
        return DriverManager.getConnection(mysqlUrl, mysqlUser, mysqlPassword);
    }
//insert
private static void insertToMysql(Connection connection, String sql) throws SQLException {
        Statement statement = connection.createStatement();
        statement.executeUpdate(sql);
        statement.close();
        connection.close();
    }
//获取库中的表
private static List<String> getDbTables(Connection connection, String sql) throws SQLException {
        List<String> list = new ArrayList<String>();
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
        while(resultSet.next()) {
            list.add(resultSet.getString("TABLE_NAME"));
            System.out.println("------------" + resultSet.getString("TABLE_NAME"));
        }
        resultSet.close();
        statement.close();
        connection.close();
        return list;
    }
//获取表字段、类型和长度
private static List<String> getTableColumn(Connection connection, String tableName) throws SQLException {
        List<String> list = new ArrayList<String>();
        DatabaseMetaData databaseMetaData = connection.getMetaData();
        ResultSet resultSet = databaseMetaData.getColumns( null, "%", tableName, "%");
        while(resultSet.next()) {
            String columnName = resultSet.getString("COLUMN_NAME");
            String columnType = resultSet.getString("TYPE_NAME");
            int datasize = resultSet.getInt("COLUMN_SIZE");
            System.out.println(columnName+" "+columnType+" "+datasize);
        }
        resultSet.close();
        connection.close();
        return list;
    }
//获取表行数
private static long getTableRowsCount(Connection connection, String sql) throws SQLException {
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
        long rowCount = 0;
        if (resultSet.next()) {
            rowCount = resultSet.getInt(1);
        }
        System.out.println(rowCount );
        resultSet.close();
        statement.close();
        connection.close();
        return rowCount;
    }
//获取表数据
private static List<Map<String, Object>> getTableData(Connection connection, String sql) throws SQLException {
        System.out.println(sql);
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
        List<Map<String, Object>>  recordsList = new ArrayList<>();
        ResultSetMetaData md = resultSet.getMetaData();//获取键名
        int columnCount = md.getColumnCount();//获取列的数量
        while (resultSet.next()) {
            Map<String, Object> orderedRecords = new LinkedHashMap<>();
            for (int i = 1; i <= columnCount; i++) {
                try {
                    orderedRecords.put(md.getColumnName(i), md.getColumnType(i) == Types.INTEGER ? resultSet.getInt(i) : resultSet.getString(i));
                } catch (Exception e) {
                    orderedRecords.put(md.getColumnName(i), resultSet.getString(i));
                }
            }
            recordsList.add(orderedRecords);
        }
        resultSet.close();
        statement.close();
        connection.close();
        return recordsList;
    }

oracle

main方法

public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        String oracleSqlQueryTables = "select table_name from user_tables";
        String oracleTableRows = "select count(0) from " + "PSI1";
        int page = 2;
        int size = 10;
        String oracleQ = page == 0 && size == 0 ? "" : " where ROWNUM BETWEEN " + (page - 1) * size  + " AND " + page * size;
        String ol = "select ID from (select t.*,rownum r from PSI1 t ) where r between " + ((page - 1) * size + 1) + " and " + page * size;
        String oracleQuerySql = page == 0 && size == 0 ? "select * from PSI1" : ol;
        try {
            oracle数据库
            connection = oracleConnection();
            getDbTables(connection, oracleSqlQueryTables);
            getTableColumn(connection, "TEST");
            getTableRowsCount(connection, oracleTableRows);
            getTableData(connection, oracleQuerySql);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

其余方法

//获取连接
    private static Connection oracleConnection() throws Exception {
        String oracleUser = "";
        String oraclePassword = "";
        String oracleUrl = "jdbc:oracle:thin:@ip:port:xe";
        String driverClassName = "oracle.jdbc.driver.OracleDriver";
        Class.forName(driverClassName);
        return DriverManager.getConnection(oracleUrl, oracleUser, oraclePassword);
    }
//下面四个方法和上面mysql调用的是同一个方法,就不赘述了
getDbTables(connection, oracleSqlQueryTables);
getTableColumn(connection, "TEST");
getTableRowsCount(connection, oracleTableRows);
getTableData(connection, oracleQuerySql);

postgresql


main方法


public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        int page = 2;
        int size = 10;
        String l = page == 0 && size == 0 ? "" : " limit " + size + " offset " + (page - 1) * size;
        String postQuerySql = "select id,age from accounts" + l;
        String postTableRows = "select count(0) from " + "accounts";
        try {
//            postGre数据库
            connection = postConnection();
            getPostTables(connection);
            getTableColumn(connection, "basic_info");
            getTableRowsCount(connection, postTableRows);
            getTableData(connection, postQuerySql);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

其余方法

//获取连接
    private static Connection postConnection() throws Exception {
        String postGreUser = "";
        String postGrePassword = "";
        String postGreUrl = "jdbc:postgresql://ip:port/test";
        String driverClassName = "org.postgresql.Driver";
        Class.forName(driverClassName);
        return DriverManager.getConnection(postGreUrl, postGreUser, postGrePassword);
    }
//获取数据库中所有表名
    private static List<String> getPostTables(Connection connection) throws SQLException {
        DatabaseMetaData metaData = connection.getMetaData();
        List<String> list = new ArrayList<String>();
        ResultSet resultSet = metaData.getTables(null, null, "%", null);
        while (resultSet.next()) {
            String tableName = resultSet.getString("TABLE_NAME");
            String tableType = resultSet.getString("TABLE_TYPE");
            if (judgeContainsStr(tableName, false) && null != tableType && tableType.equals("TABLE")) {
                System.out.println("postGre-tableName:" + tableName + ", tableType:" + tableType);
                list.add(tableName);
            }
        }
        return list;
    }
//下面三个方法和上面mysql调用的是同一个方法,就不赘述了
            getTableColumn(connection, "basic_info");
            getTableRowsCount(connection, postTableRows);
            getTableData(connection, postQuerySql);


gbase


main方法

public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        String gbaseQueryTables = "select table_name from information_schema.tables where table_schema='test'";
        String gbaseTableRows = "select count(0) from " + "mytable";
        String gbaseQuerySql = "select * from " + "mytable" + q;
        String gbaseQuerySql1 ="select `col2`,`col1` from `" + "mytable" + "`" + q;
        try {
//            gbase数据库
            connection = gbaseConnection();
            getDbTables(connection, gbaseQueryTables);
            getTableColumn(connection, "mytable");
            getTableRowsCount(connection, gbaseTableRows);
            getTableData(connection, gbaseQuerySql1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

其余方法

    private static Connection gbaseConnection() throws Exception {
        String gbaseUser = "";
        String gbasePassword = "";
        String gbaseUrl = "jdbc:gbase://ip:port/test";
        String driverClassName = "com.gbase.jdbc.Driver";
        Class.forName(driverClassName);
        return DriverManager.getConnection(gbaseUrl, gbaseUser, gbasePassword);
    }
//下面四个方法和上面mysql调用的是同一个方法,就不赘述了
            getDbTables(connection, gbaseQueryTables);
            getTableColumn(connection, "mytable");
            getTableRowsCount(connection, gbaseTableRows);
            getTableData(connection, gbaseQuerySql1);

mongo


main方法

public static void main(String[] args) {
        try {
//            mongo数据库
            MongoClient mongoClient = mongo();
            getMongoTables(mongoClient, "dmtestdb");
            getMongoTableColumn(mongoClient, "dmtestdb", "dmtestcoll");
            getMongoTableColumn1(mongoClient, "dmtestdb", "dmtestcoll");
            getMongoTableRowsCount(mongoClient, "dmtestdb", "dmtestdb");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

其他方法

    private static MongoClient mongo() {
        try {
            ServerAddress serverAddress = new ServerAddress(ip,port);
            List<ServerAddress> addrs = new ArrayList<ServerAddress>();
            addrs.add(serverAddress);
            //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
            MongoCredential credential = MongoCredential.createScramSha1Credential("dmtest", "dmtestdb", "dmlab".toCharArray());
            List<MongoCredential> credentials = new ArrayList<MongoCredential>();
            credentials.add(credential);
            System.out.println("Connect to database successfully");
            //通过连接认证获取MongoDB连接
            return new MongoClient(addrs,credentials);
        } catch (Exception e) {
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
            return null;
        }
    }
    public static List<String> getMongoTables(MongoClient mongoClient, String databaseName) {
        List<String> tableCounts = new ArrayList<>();
        MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);
        for (String collectionName : mongoDatabase.listCollectionNames()) {
            tableCounts.add(collectionName);
        }
        mongoClient.close();
        return tableCounts;
    }
    private static List<String> getMongoTableColumn(MongoClient mongoClient, String databaseName, String tableName) throws SQLException {
        MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);
        MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(tableName);
//查询集合全部数据        FindIterable<Document> cursor = mongoCollection.find();
//分页查询        FindIterable<Document> cursor = mongoCollection.find().skip(1).limit(2);
//分页查询        mongoCollection.find().skip("跳过").limit("查询几条")
//        mongoCollection.find(eq("status", "A")).skip("跳过").limit("查询几条")
//查询具体的字段                .projection(fields(include("item", "status"), excludeId()));
        FindIterable<Document> cursor = mongoCollection.find().skip(1).limit(2).projection(fields(include("name", "age", "_id"), excludeId()));
        HashMap<String, String> keyAndType = new HashMap<>();
        for (Map.Entry<String, Object> entry : cursor.first().entrySet()) {
            if (entry.getValue() instanceof Double) {
                keyAndType.put(entry.getKey(), "Double");
            } else if (entry.getValue() instanceof Integer) {
                keyAndType.put(entry.getKey(), "Integer");
            } else {
                keyAndType.put(entry.getKey(), "String");
            }
        }
        MongoCursor<Document> mongoCursor = cursor.iterator();
        List<CollectionRecords.CollectionRecord> records = Lists.newArrayList();
        while (mongoCursor.hasNext()) {
            Document loopDocument = mongoCursor.next();
            CollectionRecords.CollectionRecord collectionRecord = new CollectionRecords.CollectionRecord();
            for (Map.Entry<String, Object> entry : loopDocument.entrySet()) {
                CollectionRecords.CollectionField collectionField = new CollectionRecords.CollectionField();
                collectionField.setKey(entry.getKey());
                collectionField.setValue(entry.getValue().toString());
                collectionField.setType(keyAndType.get(entry.getKey()));
                collectionRecord.add(collectionField);
                records.add(collectionRecord);
            }
        }
//            [{"record":[{"key":"name","value":"\"bob\"","type":"[]uint8"},{"key":"age","value":"42","type":"[]uint8"},{"key":"status","value":"\"A\"","type":"[]uint8"},{"key":"ObjectId","value":"62f328222522c7b329120af3","type":"bson.ObjectId"}]},{"record":[{"key":"status","value":"\"A\"","type":"[]uint8"},{"key":"ObjectId","value":"62f328332522c7b329120afb","type":"bson.ObjectId"},{"key":"name","value":"\"ahn\"","type":"[]uint8"},{"key":"age","value":"22","type":"[]uint8"}]},{"record":[{"key":"age","value":"34","type":"[]uint8"},{"key":"status","value":"\"D\"","type":"[]uint8"},{"key":"ObjectId","value":"62f3283d2522c7b329120b14","type":"bson.ObjectId"},{"key":"name","value":"\"xi\"","type":"[]uint8"}]}]
        System.out.println("records: " + new Gson().toJson(records));
        mongoCursor.close();
        mongoClient.close();
        return null;
    }
    private static List<String> getMongoTableColumn1(MongoClient mongoClient, String databaseName, String tableName) throws SQLException {
        MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);
        ListCollectionsIterable<Document> collectionsIterable = mongoDatabase.listCollections();
        Document firstDocument = collectionsIterable.first();
        if (firstDocument != null) {
            System.out.println("first collection >>>" + firstDocument.toJson());
        }
        /** collectionsIterable.iterator() 获取 MongoCursor<Document> 游标
         * 不用担心空指针异常*/
        MongoCursor<Document> mongoCursor = collectionsIterable.iterator();
        while (mongoCursor.hasNext()) {
            Document loopDocument = mongoCursor.next();
//            collectionList.add(loopDocument);
        }
        /**关闭游标*/
        mongoClient.close();
        return null;
    }
    private static long getMongoTableRowsCount(MongoClient mongoClient, String databaseName, String tableName) throws SQLException {
        long rowCount = 0;
        MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);
        MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(tableName);
        rowCount = mongoCollection.count();
        mongoClient.close();
        System.out.println("getMongoTableRowsCount-rowCount:" + rowCount);
        return rowCount;
    }

代码较多,但应该是比较细节了,这里就不做过多的讲解了

相关实践学习
如何快速连接云数据库RDS MySQL
本场景介绍如何通过阿里云数据管理服务DMS快速连接云数据库RDS MySQL,然后进行数据表的CRUD操作。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
17天前
|
NoSQL Java 关系型数据库
Liunx部署java项目Tomcat、Redis、Mysql教程
本文详细介绍了如何在 Linux 服务器上安装和配置 Tomcat、MySQL 和 Redis,并部署 Java 项目。通过这些步骤,您可以搭建一个高效稳定的 Java 应用运行环境。希望本文能为您在实际操作中提供有价值的参考。
89 26
|
6天前
|
关系型数据库 MySQL 数据库
市场领先者MySQL的挑战者:PostgreSQL的崛起
PostgreSQL(简称PG)是世界上最先进的开源对象关系型数据库,起源于1986年的加州大学伯克利分校POSTGRES项目。它以其丰富的功能、强大的扩展性和数据完整性著称,支持复杂数据类型、MVCC、全文检索和地理空间数据处理等特性。尽管市场份额略低于MySQL,但PG在全球范围内广泛应用,受到Google、AWS、Microsoft等知名公司支持。常用的客户端工具包括PgAdmin、Navicat和DBeaver。
25 4
|
16天前
|
存储 Oracle 关系型数据库
数据库数据恢复—ORACLE常见故障的数据恢复方案
Oracle数据库常见故障表现: 1、ORACLE数据库无法启动或无法正常工作。 2、ORACLE ASM存储破坏。 3、ORACLE数据文件丢失。 4、ORACLE数据文件部分损坏。 5、ORACLE DUMP文件损坏。
63 11
|
20天前
|
JavaScript 安全 Java
java版药品不良反应智能监测系统源码,采用SpringBoot、Vue、MySQL技术开发
基于B/S架构,采用Java、SpringBoot、Vue、MySQL等技术自主研发的ADR智能监测系统,适用于三甲医院,支持二次开发。该系统能自动监测全院患者药物不良反应,通过移动端和PC端实时反馈,提升用药安全。系统涵盖规则管理、监测报告、系统管理三大模块,确保精准、高效地处理ADR事件。
|
29天前
|
Oracle 关系型数据库 数据库
Oracle数据恢复—Oracle数据库文件有坏快损坏的数据恢复案例
一台Oracle数据库打开报错,报错信息: “system01.dbf需要更多的恢复来保持一致性,数据库无法打开”。管理员联系我们数据恢复中心寻求帮助,并提供了Oracle_Home目录的所有文件。用户方要求恢复zxfg用户下的数据。 由于数据库没有备份,无法通过备份去恢复数据库。
|
1月前
|
关系型数据库 MySQL Java
MySQL索引优化与Java应用实践
【11月更文挑战第25天】在大数据量和高并发的业务场景下,MySQL数据库的索引优化是提升查询性能的关键。本文将深入探讨MySQL索引的多种类型、优化策略及其在Java应用中的实践,通过历史背景、业务场景、底层原理的介绍,并结合Java示例代码,帮助Java架构师更好地理解并应用这些技术。
33 2
|
1月前
|
存储 Oracle 关系型数据库
oracle数据恢复—Oracle数据库文件大小变为0kb的数据恢复案例
存储掉盘超过上限,lun无法识别。管理员重组存储的位图信息并导出lun,发现linux操作系统上部署的oracle数据库中有上百个数据文件的大小变为0kb。数据库的大小缩水了80%以上。 取出&并分析oracle数据库的控制文件。重组存储位图信息,重新导出控制文件中记录的数据文件,发现这些文件的大小依然为0kb。
|
22天前
|
存储 Oracle 关系型数据库
服务器数据恢复—华为S5300存储Oracle数据库恢复案例
服务器存储数据恢复环境: 华为S5300存储中有12块FC硬盘,其中11块硬盘作为数据盘组建了一组RAID5阵列,剩下的1块硬盘作为热备盘使用。基于RAID的LUN分配给linux操作系统使用,存放的数据主要是Oracle数据库。 服务器存储故障: RAID5阵列中1块硬盘出现故障离线,热备盘自动激活开始同步数据,在同步数据的过程中又一块硬盘离线,RAID5阵列瘫痪,上层LUN无法使用。
|
关系型数据库 MySQL Java
Java连接mysql的程序
<pre name="code" class="java">package com.ytu.DBTest; import java.sql.DriverManager; import java.sql.ResultSet; import com.mysql.jdbc.*; public class Test { public static void main(String[] arg
1067 0
|
1天前
|
Java
Java—多线程实现生产消费者
本文介绍了多线程实现生产消费者模式的三个版本。Version1包含四个类:`Producer`(生产者)、`Consumer`(消费者)、`Resource`(公共资源)和`TestMain`(测试类)。通过`synchronized`和`wait/notify`机制控制线程同步,但存在多个生产者或消费者时可能出现多次生产和消费的问题。 Version2将`if`改为`while`,解决了多次生产和消费的问题,但仍可能因`notify()`随机唤醒线程而导致死锁。因此,引入了`notifyAll()`来唤醒所有等待线程,但这会带来性能问题。
Java—多线程实现生产消费者

推荐镜像

更多