美文网首页
WebのJDBC连接

WebのJDBC连接

作者: 阿狸_小乖 | 来源:发表于2018-01-09 16:14 被阅读0次
    /*
     * 得到Connection
    * 1. 准备四大参数
    * 2. 加载驱动类
    * 3. 得到Connection
    */
    String driverClassName = "com.mysql.jdbc.Driver";
    String url = "jdbc:mysql://localhost:3306/ea";
    String username = "root";
    String password = "root";
    // 加载驱动类
    Class.forName(driverClassName);
    // 使用DriverManager,以及省下的3个参数,得到Connection
    Connection con = DriverManager.getConnection(url, username, password);
    

    进阶

    JdbcUtils.java
    public class JdbcUtils {
       private static Properties props = null;
       // 只在JdbcUtils类被加载时执行一次!
       static {
           // 给props进行初始化,即加载dbconfig.properties文件到props对象中
           try {
               InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("dbconfig.properties");
               props = new Properties();
               props.load(in);
           } catch(IOException e) {
               throw new RuntimeException(e);
           }
           // 加载驱动类
           try {
               Class.forName(props.getProperty("driverClassName"));
           } catch (ClassNotFoundException e) {
               throw new RuntimeException(e);
           }
       }
       
       // 获取连接!
       public static Connection getConnection() throws SQLException {
           // 得到Connection
           return DriverManager.getConnection(props.getProperty("url"),
                   props.getProperty("username"), 
                   props.getProperty("password"));
       }
    }
    

    使用

    @Test
    public void fun1() throws SQLException {
        Connection con = JdbcUtils.getConnection();
        System.out.println(con);
        Connection con1 = JdbcUtils.getConnection();
        System.out.println(con1);
    }
    

    相关文章

      网友评论

          本文标题:WebのJDBC连接

          本文链接:https://www.haomeiwen.com/subject/plqgnxtx.html