What is the difference between package com.mysql.jdbc.PreparedStatement; and java.sql.PreparedStatement?

喜你入骨 提交于 2021-02-08 05:14:53

问题


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 ?


回答1:


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:

  • When should I use an interface in java?
  • In simplest terms, what is a factory?


来源:https://stackoverflow.com/questions/12065464/what-is-the-difference-between-package-com-mysql-jdbc-preparedstatement-and-jav

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