创建连接对象的三种方式
//第一种方式 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?user=root&password=root") ; //第二种方式 //读取properties文件 Properties pro = new Properties() ; InputStream in = JdbcDemo3.class.getClassLoader().getResourceAsStream("dbcfg.properties") ; pro.load(in) ; Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", pro) ; //第三种方式 Connection conn = DriverManager.getConnection(url,user,password) ;
第二种方式通过读取properties文件获取需要的信息。
1.新建properties文件
输入文件名和扩展名(.properties)
2.编辑properties文件
3.获取properties文件信息
private static String driverClass = "" ; private static String url = "" ; private static String user = "" ; private static String password = ""; static{ ResourceBundle rb = ResourceBundle.getBundle("dbcfg") ; driverClass = rb.getString("driverClass") ; url = rb.getString("url") ; user = rb.getString("user") ; password = rb.getString("password") ; try { Class.forName(driverClass) ;//自动注册驱动 } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static Connection getConnection(){ try { return DriverManager.getConnection(url, user, password) ; } catch (SQLException e) { e.printStackTrace(); } return null ; }
时间: 2024-10-21 00:45:48