cannot find symbol PreparedStatement after JAR upgrade

∥☆過路亽.° 提交于 2020-08-10 13:15:09

问题


I just upgraded mysql jdbc connection JAR (from mysql-connector-java-5.0.5.jar to mysql-connector-java-8.0.19.jar) and the project started showing error for import statements:

import com.mysql.jdbc.PreparedStatement;

java: cannot find symbol
  symbol:   class PreparedStatement
  location: class package.ClassName 

Where to find the location or package for PreparedStatement in new jar file or is it replaced with any other class in new JAR?


回答1:


Try to replace it with:

import java.sql.PreparedStatement;

Using com.mysql.jdbc.PreparedStatement is specific to mysql, and should not be imported directly.

So unless you need MySQL specific features, it's always better to use the interface java.sql.PreparedStatement that is database independent. See also this.




回答2:


com.mysql.jdbc.PreparedStatement is an internal class to the MySQL 5.x JDBC driver. Your code should not import it. It should be using the standard java.sql.PreparedStatement class instead.

The package names have changed in the MySQL 8.x JDBC drivers, and that is what caused your code to start giving compilation errors.

Solution:

  1. Fix your code so that it doesn't import any MySQL implementation classes1. Use the java.sql.* and javax.sql.* class instead.

  2. Change your project dependencies so that the MySQL driver JAR is not a compile-time dependency. Doing that will cause any accidental source code dependencies on JDBC drivers to be flagged as compilation errors. It will also stop your IDE from making incorrect suggestions for import statements. (My guess is that that is how the bogus import got into your codebase.)

  3. If your code is (still) using Class.forName to load the JDBC driver, change it to use java.sql.DriverManager instead; see javadoc. That way you won't be burned by another change in the MySQL driver class name.


1 - Your Java code should not need to depend on MySQL-specific APIs. As far as I know, the MySQL implementation classes mirror the standard JDBC APIs, so you gain nothing by using them directly. This is not true for all vendors.



来源:https://stackoverflow.com/questions/63245300/cannot-find-symbol-preparedstatement-after-jar-upgrade

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!