WebのJDBC连接

/*
 * 得到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连接)