首页 > 学院 > 开发设计 > 正文

注册驱动器并获取连接

2019-11-14 21:47:09
字体:
来源:转载
供稿:网友
注册驱动器并获取连接

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 驱动程序的现有程序将在不作修改的情况下继续工作。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表