zoukankan      html  css  js  c++  java
  • JAVA JDBC 连接数据库

    方式一

    Driver driver = new com.mysql.jdbc.Driver();
    String url = "jdbc:mysql://localhost:3306/test";
    Properties info = new Properties();
    info.setProperty("user","root");
    info.setProperty("password","1234");
    Connection connection = driver.connect(url,info);
    System.out.println(connection);

     方式二 使用反射

    Class cl = Class.forName("com.mysql.jdbc.Driver");
    
    Driver driver = (Driver) cl.newInstance();
    String url = "jdbc:mysql://localhost:3306/test";
    Properties info = new Properties();
    info.setProperty("user","root");
    info.setProperty("password","1234");
    Connection connection = driver.connect(url,info);
    System.out.println(connection);

     方式三 使用Drivermanager

            //利用反射
            Class cl = Class.forName("com.mysql.jdbc.Driver");
    
            Driver driver = (Driver) cl.newInstance();
            String url = "jdbc:mysql://localhost:3306/test";
            String user = "root";
            String password="1234";
            DriverManager.registerDriver(driver);
            Connection connection = DriverManager.getConnection(url,user,password);
            System.out.println(connection);    

     方式4 可以省略显示的驱动加载

            String url = "jdbc:mysql://localhost:3306/test";
            String user = "root";
            String password="1234";
            //利用反射
            Class.forName("com.mysql.jdbc.Driver");
            Connection connection = DriverManager.getConnection(url,user,password);
            System.out.println(connection);

    方式5 通过配置文件加载配置信息

            InputStream is = connectTest.class.getClassLoader().getResourceAsStream("jdbcInfo.properties");
            Properties pro = new Properties();
            pro.load(is);
    
            String user = pro.getProperty("user");
            String password = pro.getProperty("password");
            String url = pro.getProperty("url");
            String driverClass = pro.getProperty("driverClass");
            //利用反射
            Class.forName(driverClass);
            Connection connection = DriverManager.getConnection(url,user,password);
            System.out.println(connection);
  • 相关阅读:
    跳跃表原理
    查看Oracle操作历史的试图
    【概念】为什么有时全表扫描比通过索引扫描效率更高
    oracle驱动表以及如何确定驱动表
    SpringBoot学习(三)-----配置Bean
    leetcode 面试题58
    leetcode 1365 有多少小于当前数字的数字
    leetcode 1342 将数字变成 0 的操作次数
    leetcode1313 解压缩编码列表
    leetcode 1071 字符串的最大公因子
  • 原文地址:https://www.cnblogs.com/superxuezhazha/p/12372837.html
Copyright © 2011-2022 走看看