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);
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容