JDBC注意事项

注册驱动

DriverManager.registerDriver()方式注册驱动

DriverManager.registerDriver(new com.mysql.jdbc.Driver()); // 该方式会注册2个驱动,mysql的Driver里面有个静态代码块,里面有注册驱动的代码。如图:
mysql Driver静态代码块注册驱动图片

Class.forName()方式注册驱动

Class.form(“com.mysql.jdbc.Driver”); // 在java.sql.DriverManager类描述有这么一段话

The DriverManager methods getConnection and getDrivers have been enhanced to support 
the Java Standard Edition Service Provider mechanism. JDBC 4.0 Drivers mustinclude the 
file META-INF/services/java.sql.Driver. This file contains the name of the JDBC 
driversimplementation of java.sql.Driver. For example, to load the my.sql.Driver class,
the META-INF/services/java.sql.Driver file would contain the entry: 

 my.sql.Driver
 
Applications no longer need to explicitly load JDBC drivers using Class.forName().
Existing programswhich currently load JDBC drivers using Class.forName() will
continue to work withoutmodification. 

翻译出来的意思就是:DriverManager方法getConnection和getDrivers已经得到了增强,以支持Java标准版服务提供程序机制。JDBC 4.0驱动程序必须包含文件META-INF/services/java.sql.Driver。这个文件包含java.sql.Driver的JDBC driversimplementation的名称。例如,加载my.sql。驱动程序类,META-INF /services/java.sql.Driver。驱动程序文件将包含条目:

my.sql.Driver

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

这个意思就是在JDBC4.0以后的版本可以不写加载驱动的代码,照样可以连接数据库进行操作。

加载数据库配置文件

配置文件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值