java代码连接数据库编码实现

依赖包:

compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.38'
compile group: 'org.mongodb', name: 'mongo-java-driver', version: '4.2.3'
compile group: 'com.oracle.database.jdbc', name: 'ojdbc8', version: '19.8.0.0'

 

public static Connection getConnection() {

        Connection conn = null;
        try {
            String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
            String user = "scott";
            String password = "tiger";

            Class.forName("oracle.jdbc.driver.OracleDriver");// 加载数据驱动
            conn = DriverManager.getConnection(url, user, password);// 连接数据库

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("加载数据库驱动失败");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("连接数据库失败");
        }
        return conn;
    }

mysql:

 public static final String url = "jdbc:mysql://192.168.31.150/information_schema";  
    public static final String name = "com.mysql.jdbc.Driver";  
    public static final String user = "root";  
    public static final String password = "";  
 
    public static Connection conn = null;  
    public static PreparedStatement pst = null;  
    public static ResultSet  ret  = null;
 
    
    public static Connection getConnection(String url,String user,String password) throws Exception{
        try {
             Class.forName(name);
             Connection connection = DriverManager.getConnection(url,user,password);//获取连接  
             if(null == connection) {
                 throw new Exception("can not connect mysql");
             }
             return connection;
        } catch (Exception e) {
            throw e;
        }
    }

mongo:

  //不通过认证获取连接数据库对象
    @SuppressWarnings("resource")
    public static MongoDatabase getConnect(String ip,int port,String databaseName){
        //连接到 mongodb 服务
        MongoClient mongoClient = new MongoClient(ip, port);
        //连接到数据库
        MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);
        //返回连接数据库对象
        return mongoDatabase;
    }

 

posted @ 2021-04-27 14:16  凉城  阅读(375)  评论(0编辑  收藏  举报