zoukankan      html  css  js  c++  java
  • 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;
        }
  • 相关阅读:
    founder面试题
    项目bug的修正
    Linux下分割、合并PDF(pdftk),用于Linux系统的6款最佳PDF页面裁剪工具
    Vim global命令和重复操作
    嵌入式linux GUI--DirectFB + GTK至尊秘笈
    让QT/Embedded支持国际化
    开篇-QT完全手册
    java多线程样例
    Windows Minifilter驱动
    poj 3735 大数量反复操作问题(矩阵高速幂)
  • 原文地址:https://www.cnblogs.com/liangblog/p/14708762.html
Copyright © 2011-2022 走看看