3

I have connected JAVA application with MySql .When i wrote PreparedStatement ps = null ; then two option for import package was showing .The two suggested package was :com.mysql.jdbc.PreparedStatement; and java.sql.PreparedStatement .And , when i import com.mysql.jdbc.PreparedStatement package they said for casting as shown below .

ps = (PreparedStatement) con.prepareStatement("INSERT INTO Authors(Name) VALUES(?)");

And when i used java.sql.PreparedStatement not need for casting in above sentence .

so, My question is : why two different import package are showing ? and why casting needed for com.mysql.jdbc.PreparedStatement package ?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Pratik
  • 167
  • 3
  • 11

1 Answers1

14

why two different import package are showing ?

Because both classes were present in your compiletime classpath and your IDE were trying to be helpful.


and why casting needed for com.mysql.jdbc.PreparedStatement package ?

Because prepareStatement() is specified to return java.sql.PreparedStatement, not com.mysql.jdbc.PreparedStatement.


The java.sql.PreparedStatement is an interface and you should be using this all the time. The MySQL one is a concrete implementation and you should not be tight coupling your JDBC code to the MySQL specific implementation. Otherwise you'd have to make a lot of changes in your code if you ever want to switch the DB server (and thus also the JDBC driver) to a different vendor like PostgreSQL. If you're using the standard JDBC interfaces from java.sql package all the time, all you would need to change is only the JDBC URL and maybe also the username and password and some DB-specific SQL statements.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 2
    ... or even if `com.mysql.jdbc.PreparedStatement` changes name/package, which the mysql developers are at liberty to do, your code will (unnecessarily) break – Bohemian Aug 22 '12 at 02:24
  • 1
    @Bohemian That was pretty prescient, because that was exactly what MySQL/Oracle did with MySQL Connector/J 8. – Mark Rotteveel Aug 04 '20 at 11:45