com.mysql.jdbc.PreparedStatement包和有什么区别?和java.sql.PreparedStatement? [英] What is the difference between package com.mysql.jdbc.PreparedStatement; and java.sql.PreparedStatement?

查看:242
本文介绍了com.mysql.jdbc.PreparedStatement包和有什么区别?和java.sql.PreparedStatement?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将Java应用程序与MySql连接起来.当我编写PreparedStatement ps = null时; 然后显示导入包的两个选项.两个建议的包是:com.mysql.jdbc.PreparedStatement;.和java.sql.PreparedStatement.而且,当我导入com.mysql.jdbc.PreparedStatement包时,它们表示要进行铸造,如下所示.

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(?)");

当我使用java.sql.PreparedStatement时,不需要在上面的句子中进行强制转换.

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

所以,我的问题是:为什么显示两个不同的导入包?以及为什么需要对com.mysql.jdbc.PreparedStatement包进行强制转换?

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

推荐答案

为什么显示两个不同的导入包?

因为这两个类都存在于您的编译时类路径中,并且您的IDE试图提供帮助.

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

以及为什么需要对com.mysql.jdbc.PreparedStatement包进行强制转换?

因为prepareStatement()已指定以返回java.sql.PreparedStatement,而不是com.mysql.jdbc.PreparedStatement.

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

java.sql.PreparedStatement界面,您应该一直使用它. MySQL是一种具体的实现,您不应将JDBC代码与MySQL特定的实现紧密结合.否则,如果您想将数据库服务器(以及JDBC驱动程序)切换到其他供应商(如PostgreSQL),则必须对代码进行大量更改.如果您一直使用java.sql包中的标准JDBC接口,则只需更改JDBC URL,可能还要更改用户名和密码以及某些特定于数据库的SQL语句.

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.

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

这篇关于com.mysql.jdbc.PreparedStatement包和有什么区别?和java.sql.PreparedStatement?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆