简体   繁体   English

在JDBC中使用class.forName

[英]Using class.forName in JDBC

Following is the code to connect to a MySQL database 以下是连接到MySQL数据库的代码

// This will load the MySQL driver, each DB has its own driver
  Class.forName("com.mysql.jdbc.Driver");
  // Setup the connection with the DB
  connect = DriverManager
      .getConnection("jdbc:mysql://localhost/feedback?"
          + "user=sqluser&password=sqluserpw");

I was learning reflections in java where the class can be obtained using Class.forName() 我正在学习Java中的思考,其中可以使用Class.forName()获取类

 Class c = Class.forName("java.awt.Button");

Was the syntax used. 是使用的语法。

My question is why the MySQL ForName did not needed to be caught in a variable ? 我的问题是为什么MySQL ForName不需要陷入变量中?

You mean why isn't the Class object saved into a variable. 您的意思是为什么Class对象没有保存到变量中。 Because it wasn't needed. 因为不需要。 The class only needed to be loaded, the actual Class object was superfluous. 该类仅需要加载,实际的Class对象是多余的。

Also these days you don't even need to do the Class.forName() anymore. 同样,这些天,您甚至不需要再执行Class.forName() The driver will be found from the classpath automatically, if you're using JDBC type 4 (pure java) drivers. 如果您使用的是JDBC 4类(纯Java)驱动程序,将从类路径中自动找到该驱动程序。

By calling forName() you force the class to be initialized (which is more than just loading it). 通过调用forName()您可以强制初始化类(不仅仅是加载它)。 In that process some static initializers run, which register that particular class with the JDBC manager code in the JDK. 在该过程中,将运行一些静态初始化程序,这些初始化程序将特定的类注册到JDK中的JDBC管理器代码中。 That makes a driver instance available internally to the JDK and it is implicitly used in all later code. 这使得驱动程序实例对JDK内部可用,并且在所有以后的代码中都隐式使用它。

Admittedly, relying on unintuitive Reflection calls is a piece of bad design by the authors of JDBC, but in the early days of Java there were less choices than today and the world of Java wasn't as tough. 诚然,依靠非直觉的Reflection调用是JDBC作者的一个不好的设计,但是在Java的早期,选择比今天少了,Java的世界并不那么艰难。 It was a language which had yet to attract serious adoption. 这是一种尚未引起认真采用的语言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM