java实现数据库连接测试是否成功

java实现数据库连接测试是否成功

支持oracle、mysql的数据库连接测试

代码

package com.bczc.common.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;

public class ConnTest {
    //数据库类型 0:mysql 1:oracle
    private static String databaseType;
    //数据库名称
    private static String databaseName;
    //用户名
    private static String userName;
    //密码
    private static String password;
    //地址
    private static String address;
    //端口  默认端口:mqsql3306 oracle1521
    private static String port;


    /**
     * @param databaseType //0:mysql 1:oracle
     * @param databaseName
     * @param userName
     * @param password
     * @param address
     * @param port
     */
    ConnTest(String databaseType, String databaseName, String userName, String password, String address, String port) {
        this.databaseType = databaseType;
        this.databaseName = databaseName;
        this.userName = userName;
        this.password = password;
        this.address = address;
        this.port = port;
    }

    private static String conn(String driverName, String url) {
        try {
            Class.forName(driverName);
            Connection connection = DriverManager.getConnection(url, userName, password);
            connection.close();
        } catch (Exception e) {
            return "连接失败";
        }
        return "连接成功";
    }

    private static String sqlConn() {
        String driverName = null;
        if ("0".equals(databaseType)) {
            //mysql
            driverName = "com.mysql.cj.jdbc.Driver";
            String url = "jdbc:mysql://" + address + ":" + port + "/" + databaseName + "?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8";
            return conn(driverName, url);
        } else if ("1".equals(databaseType)) {
            //oracle
            driverName = "oracle.jdbc.driver.OracleDriver";
            String url = "jdbc:oracle:thin:@" + address + ":" + port + ":" + databaseName;
            return conn(driverName, url);
        }
        return "连接成功";
    }

    public static void main(String[] args) {
        new ConnTest("0", "bczc", "root", "root", "192.168.1.113", "3306");
        System.out.println("Mysql"+sqlConn());
        new ConnTest("1", "ckwl", "ckwl", "ckwl123", "localhost", "1521");
        System.out.println("Oracle"+sqlConn());
    }
}

效果

Mysql连接成功
Oracle连接成功

你可能感兴趣的:(Java,Mysql,Oracle)