啃不动地大坚果

注册驱动器并获取连接

1.三种注册驱动器的方法

(1)Class.forName("com.mysql.jdbc.Driver");

(2)System.setProperty("jdbc.drivers","com.mysql.jdbc.Driver");

(3)极不推荐 DriverManager.registerDrivers(new com.mysql.jdbc.Driver());

2.三种获取连接的方式

(1)Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","123456");

(2)Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/test?user=root&password=123456");

(3)Connection conn=DriverManager.getConnection(strUrl,props);

database.properties配置文件

jdbc.drivers=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://localhost:3306/test

jdbc.user=root

jdbc.password=123456

...

 

Properties props=new Properties();

FileInputStream in=new FileInputStream("database.properties");  //获取database.properties配置文件

props.load(in);

in.close();

String strDriver=props.getProperty("jdbc.drivers");

String strUrl=props.getProperty("jdbc.url");

System.setProperty("jdbc.drivers",strDriver); 

Connection conn=DriverManager.getConnection(strUrl,props);

3.追记

在JDBC4.0中已经不需要再显示的注册驱动了

以下是JDK6.0文档中的建议:

 JDBC 4.0 驱动程序包中必须包括 META-INF/services/java.sql.Driver 文件。此文件包含java.sql.Driver 的 JDBC 驱动程序实现的名称。例如,要加载 my.sql.Driver 类,META-INF/services/java.sql.Driver 文件需要包含下面的条目:

 my.sql.Driver

应用程序不再需要使用 Class.forName() 显式地加载 JDBC 驱动程序。当前使用 Class.forName() 加载 JDBC 驱动程序的现有程序将在不作修改的情况下继续工作。

posted on 2014-11-06 21:20  啃不动地大坚果  阅读(309)  评论(0编辑  收藏  举报

导航