JDBC-接口的实现 [英] JDBC- Implementation of interfaces

查看:109
本文介绍了JDBC-接口的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JDBC中,为了在DB中连接和执行语句,我们主要使用Connection,Statement和ResultSet作为接口。但是它们的相应对象后来用于运行createStatement(),executeQuery(),next()等方法。哪些类实现了这些方法?
为什么它被称为连接对象而不是实现的类对象?

In JDBC, to connect and execute statements in DB we mainly make use of Connection,Statement and ResultSet which are interfaces. But their corresponding objects is later used to run methods like createStatement(),executeQuery(),next() etc.Which class implements these methods? Why it is called as connection object instead of implemented class object?

推荐答案

在JDBC中,首先注册一个驱动程序致电

In JDBC you first register a driver by calling

Class.forName('classname')

加载Database类并使用 DriverManager

which loads the Database class and registers that class with DriverManager

当您说 DriverManager.getConnection()时 - 它返回 java.sql.Connection (根据规范的合同) )

When you say DriverManager.getConnection() - It returns you java.sql.Connection (the contract as per specification)


哪个类实现了这些方法?

Which class implements these methods?

实际实现由数据库供应商提供,例如Oracle,MySQL。

The actual implementation is provided by the database vendor, for e.g. Oracle, MySQL.


为什么它被称为连接对象而不是实现类
对象?

Why it is called as connection object instead of implemented class object?

因为你代码接口而非实现(良好的编码习惯)。

Because you code to Interface and not implementation (good coding practice).

如果你想要,你可以在供应商jar中查找并找到哪个类实现了Connection而不是

If you want you can look up in the vendor jar and find which class implements Connection then instead of

Connection connection = DriverManager.getConnection()

你可以写

VendorConnectionImpl vendorConnection = (VendorConnectionImpl)DriverManager.getConnection()

上面的内容可以使用但是它会将你绑定到特定的实现。

This above will work but then it will bind you with that specific implementation.

如果你想从vendor1转到vendor2你不能这样做,首先你必须按照vendor2 API改变上面的代码,但如果你使用第一种方法,你可以无需更改代码即可从供应商转移到供应商。

If you want to move from vendor1 to vendor2 you cannot do that, first you will have to change the above code as per vendor2 API, But if you use the first approach you can move from Vendor to Vendor without having pain of changing your code.

这篇关于JDBC-接口的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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