JDBC-Interview Questions翻译

原文:https://www.tutorialspoint.com/jdbc/jdbc_interview_questions.htm

因为工作中需要要分享Sharding-jdbc,希望从两个点进行分享,第一是项目中Sharding-jdbc的具体使用,做demo,第二是原理的深入研究。

特此重温了JDBC的内容。

如上地址是一个非常简单易学的外国网站tutorialspoint,很简单基础,容易理解上手,包含了很多框架的简易入门教程和Interview题库,很是喜欢。国内极客,易白教程都对此文档有部分翻译,JDBC Tutorial ,JDBC Examples,不过都忽略了非常棒的一部分,就是JDBC Useful Resources。感觉很有意思,如下就是我对JDBC-Interview Questions的翻译,很精简直白的英文,如果有哪些疏漏的地方,还望大家指出。

因为很喜欢一边英文一边中文的对照方式,所以这次还会对比进行翻译,便于参考和对照。

ps: 这次翻译感受,英文文档有的时候比中文的更加容易理解,更加强大 简单 完善,并没有我们想象中的那么难。

What is JDBC?

JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases.

JDBC全称为Java Database Connectivity,它是Java编程语言和各种数据库之间独立于数据库的连接的标准Java API。

Discribe a general JDBC Architecture

General JDBC Architecture consists of two layers JDBC API (This provides the application-to-JDBC Manager connection) and JDBC Driver API (This supports the JDBC Manager-to-Driver Connection).

通用JDBC体系结构由两层够成。JDBC API(这提供了应用程序到JDBC管理器连接)和JDBC驱动程序API(这支持JDBC管理器到驱动程序连接)组成。

What are the common JDBC API components?

JDBC API consists of following interfaces and classes DriverManager, Driver, Connection, Statement, ResultSet, SQLException.

JDBC API由以下接口和类组成,DriverManager, Driver, Connection, Statement, ResultSet, SQLException.

What is a JDBC DriverManager?

JDBC DriverManager is a class that manages a list of database drivers. It matches connection requests from the java application with the proper database driver using communication subprotocol.

 JDBC DriverManager是一个管理数据库驱动程序列表的类。它使用通信子协议将来自java应用程序的连接请求与正确的数据库驱动程序进行匹配。

What is a JDBC Driver?

JDBC driver is an interface enabling a Java application to interact with a database. To connect with individual databases, JDBC requires drivers for each database. The JDBC driver gives out the connection to the database and implements the protocol for transferring the query and result between client and database.

 JDBC驱动程序是一个使Java应用程序与数据库交互的接口。要连接各个数据库,JDBC需要针对每个数据库匹配相应的驱动程序。 JDBC驱动程序提供与数据库的连接,并且实现了用于在客户端和数据库之间传输查询和结果的协议。

What is a connection?

Connection interface consists of methods for contacting a database. The connection object represents communication context.

连接接口包含用于联系数据库的方法。连接对象表示通信上下文。

What is a statement?

Statement encapsulates an SQL statement which is passed to the database to be parsed, compiled, planned and executed.

 Statement封装了一个SQL语句,该语句被传递给数据库以进行解析,编译,计划和执行。

What is a ResultSet?

These objects hold data retrieved from a database after you execute an SQL query using Statement objects. It acts as an iterator to allow you to move through its data. The java.sql.ResultSet interface represents the result set of a database query.

 在使用Statement对象执行SQL查询后,这些对象保存从数据库检索的数据。它充当迭代器,允许您遍历其数据。 java.sql.ResultSet接口表示数据库查询的结果集。

What are types of ResultSet?

There are three constants which when defined in result set can move cursor in resultset backward, forward and also in a particular row.

  • ResultSet.TYPE_FORWARD_ONLY − The cursor can only move forward in the result set.

  • ResultSet.TYPE_SCROLL_INSENSITIVE − The cursor can scroll forwards and backwards, and the result set is not sensitive to changes made by others to the database that occur after the result set was created.

  • ResultSet.TYPE_SCROLL_SENSITIVE − The cursor can scroll forwards and backwards, and the result set is sensitive to changes made by others to the database that occur after the result set was created.

 有三个常量,当在结果集中定义时,可以在结果集中向后,向前和在特定行中移动光标。 

    ResultSet.TYPE_FORWARD_ONLY - 光标只能在结果集中向前移动。 

    ResultSet.TYPE_SCROLL_INSENSITIVE - 游标可以向前和向后滚动,结果集对创建结果集后其他人对数据库所做的更改不敏感。 

    ResultSet.TYPE_SCROLL_SENSITIVE - 游标可以向前和向后滚动,结果集对创建结果集后其他人对数据库所做的更改很敏感。

What are the basic steps to create a JDBC application?

Following are the basic steps to create a JDBC application

  • Import packages containing the JDBC classes needed for database programming.

  • Register the JDBC driver, so that you can open a communications channel with the database.

  • Open a connection using the DriverManager.getConnection () method.

  • Execute a query using an object of type Statement.

  • Extract data from result set using the appropriate ResultSet.getXXX () method.

  • Clean up the environment by closing all database resources relying on the JVM's garbage collection.

以下是创建JDBC应用程序的基本步骤

    Import包含数据库编程所需的JDBC类的包。 

    注册JDBC驱动程序,这样就可以打开与数据库的通信通道。 

    使用DriverManager.getConnection()方法打开连接。 

    使用Statement类型的对象执行查询。 

    使用适当的ResultSet.getXXX()方法从结果集中提取数据。 

    通过关闭依赖于JVM垃圾回收的所有数据库资源来清理环境。

What are JDBC drivers?

There are four types of JDBC drivers

  • JDBC-ODBC Bridge plus ODBC driver − also called Type 1 calls native code of the locally available ODBC driver.

  • Native-API, partly Java driver − also called Type 2 calls database vendor native library on a client side. This code then talks to database over network.

  • JDBC-Net, pure Java driver − also called Type 3 the pure-java driver that talks with the server-side middleware that then talks to database.

  • Native-protocol, pure Java driver − also called Type 4 the pure-java driver that uses database native protocol.

有四种类型的JDBC驱动程序

    JDBC-ODBC Bridge和ODBC驱动程序 - 也称为Type 1调用本地可用ODBC驱动程序的本机代码。 

    Native-API,部分是Java驱动程序 - 在客户端也称为Type 2调用数据库供应商本机库。然后,此代码通过网络与数据库通信。 

   JDBC-Net,纯Java驱动程序 - 也称为Type 3纯Java驱动程序,它与服务器端中间件进行通信,然后与数据库进行通信。 

   Native-protocol,纯Java驱动程序 - 也称为Type 4,它是使用数据库本机协议的纯java驱动程序。

When should each of the JDBC driver type be used?

Following is a list as to when the four types of drivers can be used

  • If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is 4.

  • If your Java application is accessing multiple types of databases at the same time, type 3 is the preferred driver.

  • Type 2 drivers are useful in situations where a type 3 or type 4 driver is not available yet for your database.

  • The type 1 driver is not considered a deployment-level driver and is typically used for development and testing purposes only.

以下是关于何时可以使用四种类型的驱动程序的列表

如果您正在访问一种类型的数据库,例如Oracle,Sybase或IBM,则首选驱动程序类型为4. 

如果您的Java应用程序正在访问同时有多种类型的数据库,类型3是首选驱动程序。 


2类型驱动程序在数据库尚未提供类型3或类型4驱动程序的情况下非常有用。 

类型1驱动程序不被视为部署级驱动程序,通常仅用于开发和测试目的。

Which type of JDBC driver is the fastest one?

JDBC Net pure Java driver(Type 4) is the fastest driver because it converts the JDBC calls into vendor specific protocol calls and it directly interacts with the database.

 JDBC Net纯Java驱动程序(类型4)是最快的驱动程序,因为它将JDBC调用转换为供应商特定的协议调用,并且它直接与数据库交互。

Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?

No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.

不可以。使用JDBC-ODBC Bridge时,每个连接只能打开一个Statement对象。

What are the standard isolation levels defined by JDBC?

The standard isolation levels are

  • TRANSACTION_NONE

  • TRANSACTION_READ_COMMITTED

  • TRANSACTION_READ_UNCOMMITTED

  • TRANSACTION_REPEATABLE_READ

  • TRANSACTION_SERIALIZABLE

标准的隔离级别是:不隔离,读提交,读未提交,重复读,序列化。

What is the design pattern followed by JDBC?

JDBC architecture decouples an abstraction from its implementation. Hence JDBC follows a bridge design pattern. The JDBC API provides the abstraction and the JDBC drivers provide the implementation. New drivers can be plugged-in to the JDBC API without changing the client code.

JDBC体系结构将抽象与其实现分离。因此JDBC遵循桥接设计模式。 JDBC API提供抽象,JDBC驱动程序提供实现。可以在不更改客户端代码的情况下将新驱动程序插入JDBC API。

What are the different types of JDBC Statements?

Types of statements are

  • Statement − regular SQL statement.

  • PreparedStatement − more efficient than statement due to pre-compilation of SQL.

  • CallableStatement − to call stored procedures on the database.

Statements类型为

   Statement - 常规SQL语句。 

   PreparedStatement - 由于预编译SQL而比语句更有效。 

   CallableStatement - 调用数据库上的存储过程。

What is difference between statement and prepared statement?

Prepared statements offer better performance, as they are pre-compiled. Prepared statements reuse the same execution plan for different arguments rather than creating a new execution plan every time. Prepared statements use bind arguments, which are sent to the database engine. This allows mapping different requests with same prepared statement but different arguments to execute the same execution plan. Prepared statements are more secure because they use bind variables, which can prevent SQL injection attack.

Prepared statements 提供了更好的性能,因为它们是预编译的。准备好的语句为不同的参数重用相同的执行计划,而不是每次都创建一个新的执行计划。 Prepared语句使用绑定参数,这些参数被发送到数据库引擎。这允许使用相同的 prepared statement 但不同的参数映射不同的请求以执行相同的执行计划。 Prepared statements 更安全,因为它们使用绑定变量,可以防止SQL注入攻击。

How do you register a driver?

There are 2 approaches for registering the Driver

  • Class.forName() − This method dynamically loads the driver's class file into memory, which automatically registers it. This method is preferable because it allows you to make the driver registration configurable and portable.

  • DriverManager.registerDriver() − This static method is used in case you are using a non-JDK compliant JVM, such as the one provided by Microsoft.

Class.forName() - 此方法将驱动程序的类文件动态加载到内存中,自动注册它。此方法是首选,因为它允许您使驱动程序注册可配置和可移植。 

DriverManager.registerDriver() - 如果您使用的是非JDK兼容的JVM(例如Microsoft提供的JVM),则使用此静态方法。

What are the benefits of JDBC 4.0?

Here are few advantages of JDBC 4.0

  • Auto loading of JDBC driver class. In the earlier versions we had to manually register and load drivers using class.forName.

  • Connection management enhancements. New methods added to javax.sql.PooledConnection.

  • DataSet Implementation of SQL using annotations.

  • SQL XML support.

以下是JDBC 4.0 

   自动加载JDBC驱动程序类的一些优点。在早期版本中,我们必须使用class.forName手动注册和加载驱动程序。 

   连接管理增强功能。添加到javax.sql.PooledConnection的新方法。 

   DataSet使用注释实现SQL。 

   SQL XML支持。

What do you mean by fastest type of JDBC driver?

JDBC driver performance or fastness depends on a number of issues Quality of the driver code, size of the driver code, database server and its load, Network topology, Number of times your request is translated to a different API.

JDBC驱动程序性能或速度取决于许多问题驱动程序代码的质量,驱动程序代码的大小,数据库服务器及其负载,网络拓扑,请求转换为其他API的次数。

In real time project which driver did you use?

Tell about your real time experience.

讲述你项目的实际应用。

 

How do you create a connection object?

There are 3 overloaded DriverManager.getConnection() methods to create a connection object.

 有3个重载的DriverManager.getConnection()方法来创建连接对象

getConnection(String url, String user, String password)Using a database URL with a username and password. For example

getConnection(String url,String user,String password)使用带有用户名和密码的数据库URL。例如

String URL = "jdbcoraclethin@amrood1521EMP";
String USER = "username";
String PASS = "password"
Connection conn = DriverManager.getConnection(URL, USER, PASS);
getConnection(String url)Using only a database URL. For example
String URL = "jdbcoraclethinusername/password@amrood1521EMP";
Connection conn = DriverManager.getConnection(URL);
getConnection(String url, Properties prop)Using a database URL and a Properties object. For example
String URL = "jdbcoraclethin@amrood1521EMP";
Properties info = new Properties( );
info.put( "user", "username" );
info.put( "password", "password" );

How can I determine whether a Statement and its ResultSet will be closed on a commit or rollback?

Use the DatabaseMetaData methods supportsOpenStatementsAcrossCommit() and supportsOpenStatementsAcrossRollback() to check.

使用数据库数据信息方法 supportsOpenStatementsAcrossCommit() 和supportsOpenStatementsAcrossRollback()来检查一下。

Is there a practical limit for the number of SQL statements that can be added to an instance of a Statement object?

The specification makes no mention of any size limitation for Statement.addBatch(), this is dependent, on the driver.

规范没有提到Statement.addBatch()的任何大小限制,这取决于驱动程序。

How cursor works in scrollable result set?

There are several methods in the ResultSet interface that involve moving the cursor, like beforeFirst(), afterLast(), first(), last(), absolute(int row), relative(int row), previous(), next(), getRow(), moveToInsertRow(), moveToCurrentRow().

 ResultSet接口中有几个涉及移动游标的方法,如beforeFirst(),afterLast(),first(),last(),absolute(int row),relative(int row),previous(),next() ,getRow(),moveToInsertRow(),moveToCurrentRow()。

How can you view a result set?

ResultSet interface contains get methods for each of the possible data types, and each get method has two versions

  • One that takes in a column name.

  • One that takes in a column index.

For e.g. getInt(String columnName), getInt(int columnIndex)

 ResultSet接口包含每种可能数据类型的get方法,每个get方法都有两个版本

    一个接受列名。 

   一个接受列索引的。 

For例如getInt(String columnName),getInt(int columnIndex)

How do you update a result set?

ResultSet interface contains a collection of update methods for updating the data of a result set. Each update method has two versions for each data type

  • One that takes in a column name.

  • One that takes in a column index.

These methods change the columns of the current row in the ResultSet object, but not in the underlying database. To update your changes to the row in the database, you need to invoke one of the following methods

updateRow(), deleteRow(), refreshRow(), cancelRowUpdates(), insertRow()

 ResultSet接口包含一组更新方法,用于更新结果集的数据。每种更新方法对于每种数据类型都有两个版本

    一个接受列名称。 

    一个接受列索引的。 

这些方法更改ResultSet对象中当前行的列,但不更改基础数据库中的列。要更新对数据库中行的更改,需要调用以下方法之一

updateRow(),deleteRow(),refreshRow(),cancelRowUpdates(),insertRow()

How does JDBC handle the data types of Java and database?

The JDBC driver converts the Java data type to the appropriate JDBC type before sending it to the database. It uses a default mapping for most data types. For example, a Java int is converted to an SQL INTEGER.

 JDBC驱动程序在将Java数据类型发送到数据库之前将其转换为适当的JDBC类型。它使用大多数数据类型的默认映射。例如,Java int转换为SQL INTEGER。

What causes "No suitable driver" error?

"No suitable driver" is occurs during a call to the DriverManager.getConnection method, may be of any of the following reason

  • Due to failing to load the appropriate JDBC drivers before calling the getConnection method.

  • It can be specifying an invalid JDBC URL, one that is not recognized by JDBC driver.

  • This error can occur if one or more the shared libraries needed by the bridge cannot be loaded.

在调用DriverManager.getConnection方法期间出现“没有合适的驱动程序”,可能是以下任何原因

    由于在调用getConnection方法之前未能加载相应的JDBC驱动程序。 

    它可以指定无效的JDBC URL,JDBC驱动程序无法识别该URL。 

    如果无法加载桥所需的一个或多个共享库,则会发生此错误。

How do you handle SQL NULL values in Java?

SQL's use of NULL values and Java's use of null are different concepts. There are three tactics you can use

  • Avoid using getXXX( ) methods that return primitive data types.

  • Use wrapper classes for primitive data types, and use the ResultSet object's wasNull( ) method to test whether the wrapper class variable that received the value returned by the getXXX( ) method should be set to null.

  • Use primitive data types and the ResultSet object's wasNull( ) method to test whether the primitive variable that received the value returned by the getXXX( ) method should be set to an acceptable value that you've chosen to represent a NULL.

SQL使用NULL值和Java使用null是不同的概念。您可以使用三种策略

    避免使用返回原始数据类型的getXXX()方法。

    对原始数据类型使用包装类,并使用ResultSet对象的wasNull()方法来测试接收getXXX()方法返回的值的包装类变量是否应设置为null。

    使用原始数据类型和ResultSet对象的wasNull()方法来测试接收getXXX()方法返回的值的原始变量是否应设置为您选择表示NULL的可接受值。

What does setAutoCommit do?

When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed right after it is executed. By setting auto-commit to false no SQL statements will be committed until you explicitly call the commit method.

创建连接时,它处于自动提交模式。这意味着每个单独的SQL语句都被视为一个事务,并在执行后立即自动提交。通过将auto-commit设置为false,在显式调用commit方法之前,不会提交任何SQL语句。

Why will you set auto commit mode to false?

Following are the reasons

  • To increase performance.

  • To maintain the integrity of business processes.

  • To use distributed transactions.

 以下是

      提高性能的原因。 

     维护业务流程的完整性。 

     使用分布式事务。

What is SavePoint? Give an example.

A savepoint marks a point that the current transaction can roll back to. Instead of rolling all of its changes back, it can choose to roll back only some of them. For example, suppose you

  • start a transaction.

  • insert 10 rows into a table.

  • set a savepoint.

  • insert another 5 rows.

  • rollback to the savepoint.

  • commit the transaction.

After doing this, the table will contain the first 10 rows you inserted. The other 5 rows will have been deleted by the rollback. A savepoint is just a marker that the current transaction can roll back to.

保存点标记当前事务可以回滚到的点。它可以选择仅回滚其中的一些,而不是将所有更改都回滚。例如,假设你

    启动一个事务。 

   将10行插入表中。 

   设置一个保存点。 

   插入另外5行。 

   回滚到保存点。 

   提交交易。 

   执行此操作后,该表将包含您插入的前10行。其他5行将被回滚删除。保存点只是当前事务可以回滚到的标记。

What are SQL warning?

SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do. They simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method.

 SQLWarning对象是SQLException的子类,用于处理数据库访问警告。警告不会像例外那样停止执行应用程序。他们只是提醒用户某些事情没有按计划发生。可以在Connection对象,Statement对象(包括PreparedStatement和CallableStatement对象)或ResultSet对象上报告警告。这些类中的每一个都有一个getWarnings方法。

Why would you use a batch process?

Batch Processing allows you to group related SQL statements into a batch and submit them with one call to the database.

批处理允许您将相关的SQL语句分组到批处理中,并通过一次调用数据库来提交它们。

What are the steps followed to create a batch process?

Typical sequences of steps to use Batch Processing with Statement or PrepareStatement Object are

  • In case of Batch processing using PrepareStatement object, create SQL statements with placeholders.

  • Create a Statement or PrepareStatement object using either createStatement() or prepareStatement() methods respectively.

  • Set auto-commit to false using setAutoCommit().

  • Add as many as SQL statements you like into batch using addBatch() method on created statement object.

  • Execute all the SQL statements using executeBatch() method on created statement object.

  • Finally, commit all the changes using commit() method.

使用Statement或PrepareStatement对象进行批处理的典型步骤序列是

    如果使用PrepareStatement对象进行批处理,请使用占位符创建SQL语句。 

    分别使用createStatement()或prepareStatement()方法创建Statement或PrepareStatement对象。 

    使用setAutoCommit()将auto-commit设置为false。 
 
    在创建的语句对象上使用addBatch()方法将您喜欢的SQL语句添加到批处理中。 

    在创建的语句对象上使用executeBatch()方法执行所有SQL语句。 

    最后,使用commit()方法提交所有更改。

What is a Stored Procedure and how do you call it in JDBC?

A stored procedure is a group of SQL statements that form a logical unit and perform a particular task. For example operations on an employee database (hire, fire, promote, lookup) could be coded as stored procedures executed by application code. Stored procedures can be called using CallableStatement class in JDBC API. For example the following code demonstrates this

 存储过程是一组SQL语句,它们构成逻辑单元并执行特定任务。例如,员工employee 数据库上的操作(hire, fire, promote, lookup)可以编码为由应用程序代码执行的存储过程。可以使用JDBC API中的CallableStatement类调用存储过程。例如,以下代码演示了这一点

CallableStatement cs = con.prepareCall("{call MY_SAMPLE_STORED_PROC}");
ResultSet rs = cs.executeQuery();

What is JDBC SQL escape syntax?

The escape syntax gives you the flexibility to use database specific features unavailable to you by using standard JDBC methods and properties.

The general SQL escape syntax format is as follows

{keyword 'parameters'}.

JDBC defines escape sequences that contain the standard syntax for the following language features

  • Date, time, and timestamp literals (d, t, ts Keywords).

  • Scalar functions such as numeric, string, and data type conversion functions(fn Keyword).

  • Outer joins(oj Keyword)

  • Escape characters for wildcards used in LIKE clauses(escape Keyword).

  • Procedure calls(call Keyword).

使用转义语法,您可以灵活地使用标准JDBC方法和属性来使用您无法使用的数据库特定功能。 

一般的SQL转义语法格式如下

{keyword'parameters'}。 
JDBC定义包含以下语言功能

    Date,time和timestamp literals(d,t,ts Keywords)的标准语法的转义序列。 

    Scalar函数,如数字,字符串和数据类型转换函数(fn Keyword)。 

    外连接(oj关键字)

    转换LIKE子句中使用的通配符的转义字符(转义关键字)。 

    Procedure call(调用Keyword)。

What is a transaction?

A transaction is a logical unit of work. To complete a logical unit of work, several actions may need to be taken against a database. Transactions are used to provide data integrity, correct application semantics, and a consistent view of data during concurrent access.

事务是一个逻辑工作单元。要完成逻辑工作单元,可能需要对数据库采取若干操作。事务用于在并发访问期间提供数据完整性,正确的应用程序语义和一致的数据视图。

How will you insert multiple rows into a database in a single transaction?

Follow steps as below

//turn off the implicit commit
Connection.setAutoCommit(false);
//..your insert/update/delete goes here
Connection.Commit();
//a new transaction is implicitly started.

When will you get the message "No suitable Driver"?

When a Connection request is issued, the DriverManager asks each loaded driver if it understands the URL sent. When the URL passed is not properly constructed, then the "No Suitable Driver" message is returned.

发出连接请求时,DriverManager会询问每个加载的驱动程序是否理解发送的URL。如果未正确构造传递的URL,则返回“No Suitable Driver”消息。

What is the difference between execute,executeQuery,executeUpdate?

  • boolean execute() - Executes the any kind of SQL statement.

  • ResultSet executeQuery() - This is used generally for reading the content of the database. The output will be in the form of ResultSet. Generally SELECT statement is used.

  • int executeUpdate() - This is generally used for altering the databases. Generally DROP TABLE or DATABASE, INSERT into TABLE, UPDATE TABLE, DELETE from TABLE statements will be used in this. The output will be in the form of int which denotes the number of rows affected by the query.

    boolean execute() - 执行任何类型的SQL语句。 

   ResultSet executeQuery() - 这通常用于读取数据库的内容。输出将采用ResultSet的形式。通常使用SELECT语句。 

   int executeUpdate() - 这通常用于更改数据库。通常在这里使用DROP TABLE或DATABASE,INSERT到TABLE,UPDATE TABLE,DELETE from TABLE语句。输出将采用int的形式,表示受查询影响的行数。

Why do you have to close database connections in Java?

You need to close the resultset, the statement and the connection. If the connection has come from a pool, closing it actually sends it back to the pool for reuse. We can do this in the finally{} block, such that if an exception is thrown, you still get the chance to close this.

您需要关闭结果集,语句和连接。如果连接来自数据库连接池,则关闭它实际上会将其发送回池以供重用。我们可以在finally {}块中执行此操作,这样如果抛出异常,您仍然有机会关闭它。

What is the user of blob,clob datatypes in JDBC?

These are used to store large amount of data into database like images, movie etc which are extremely large in size.

这些用于将大量数据存储到数据库中,如图像,电影等,它的大小很大。

Resultset is an interface,how does it support rs.Next()?

Every vendor of Database provides implementation of ResultSet & other interfaces, through the Driver.

每个Database的供应商都通过Driver提供ResultSet和其他接口的实现。

What is Connection Pooling?

Connection Pooling is a technique used for reuse of physical connections and reduced overhead for your application. Connection pooling functionality minimizes expensive operations in the creation and closing of sessions.Database vendor's help multiple clients to share a cached set of connection objects that provides access to a database. Clients need not create a new connection everytime to interact with the database.

 连接池是一种用于重用物理连接并减少应用程序开销的技术。连接池功能最大限度地减少了创建和关闭会话的昂贵操作。数据库供应商帮助多个客户端共享一组缓存连接对象,以提供对数据库的访问。客户端无需每次都创建新连接以与数据库进行交互。

How do you implement connection pooling?

If you use an application server like WebLogic, WebSphere, jBoss, Tomcat. , then your application server provides the facilities to configure for connection pooling. If you are not using an application server then components like Apache Commons DBCP Component can be used.

 如果您使用WebLogic,WebSphere,jBoss,Tomcat等应用程序服务器。 ,然后您的应用程序服务器提供配置连接池的工具。如果您不使用应用程序服务器,则可以使用Apache Commons DBCP组件等组件.

Out of byte[] or a java.sql.Blob, Which has best performance when used to manipulate data from database?

java.sql.Blob has better performance as it does not extract any data from the database until you explicitly ask it to.

java.sql.Blob具有更好的性能,因为在您明确要求之前,它不会从数据库中提取任何数据。

 

Out of String or a java.sql.Clob, which has best performance when used to manipulate data from database?

java.sql.Clob has better performance as it does not extract any data from the database until you explicitly ask it to.

 java.sql.Clob具有更好的性能,因为在您明确要求之前,它不会从数据库中提取任何数据。

Suppose the SELECT returns 1000 rows, then how to retrieve the first 100 rows , then go back and retrieve the next 100 rows?

Use the Statement.setFetchSize method to indicate the size of each database fetch.

使用Statement.setFetchSize方法指示每个数据库提取的大小。

What does the Class.forName("MyClass") do ?

Class.forName("MyClass")

  • Loads the class MyClass.

  • Execute any static block code of MyClass.

  • Returns an instance of MyClass.

Class.forName(“MyClass”)

    加载MyClass类。 

    执行MyClass的任何静态块代码。 

    返回MyClass的一个实例。

When you say Class.forName() loads the driver class, does it mean it imports the driver class using import statement?

No, it doesn't. An import statement tells the compiler which class to look for. Class.forName() instructs the Classclass to find a class-loader and load that particular Class object into the memory used by the JVM.

不,它没有。 import语句告诉编译器要查找的类。 Class.forName()指示Classclass查找类加载器并将该特定Class对象加载到JVM使用的内存中。

What we set the attribute Concurrency in ResultSet?

The ResultSet concurrency determines whether the ResultSet can be updated, or only read. A ResultSet can have one of two concurrency levels

  • ResultSet.CONCUR_READ_ONLY − means that the ResultSet can only be read.

  • ResultSet.CONCUR_UPDATABLE − means that the ResultSet can be both read and updated.

ResultSet并发性确定ResultSet是可以更新还是仅读取。 ResultSet可以具有两个并发级别之一

    ResultSet.CONCUR_READ_ONLY - 表示只能读取ResultSet。 

    ResultSet.CONCUR_UPDATABLE - 表示可以同时读取和更新ResultSet。

What are the differences between setMaxRows(int) and setFetchSize(int)?

The difference between setFetchSize(int) and setMaxRow(int) are

  • setFetchSize(int) defines the number of rows that will be read from the database when the ResultSet needs more rows. setFetchSize(int) affects how the database returns the ResultSet data.

  • setMaxRows(int) method of the ResultSet specifies how many rows a ResultSet can contain at a time. setMaxRows(int) affects the client side JDBC object.

setFetchSize(int)和setMaxRow(int)之间的区别是

     当需要读取更多行时,setFetchSize(int)定义ResultSet需要从数据库中读取相应的行数。 setFetchSize(int)会影响数据库如何返回ResultSet数据的方式。

     ResultSet的setMaxRows(int)方法指定ResultSet一次可以包含的行数。 setMaxRows(int)影响客户端JDBC对象。

What is a RowSet?

A JDBC RowSet object holds tabular data in a way that makes it more flexible and easier to use than a result set. A RowSet objects are JavaBeans components.

JDBC RowSet对象以某种方式保存表格数据,使其比结果集更灵活,更易于使用。 RowSet对象是JavaBeans组件。

What are different types of RowSet objects?

There are two types of RowSet

  • Connected A connected RowSet Object is permanent in nature. It doesn't terminate until the application is terminated.

  • Disconnected A disconnected RowSet object is ad-hoc in nature. Whenever it requires retrieving data from the database, it establishes the connection and closes it upon finishing the required task. The data that is modified during disconnected state is updated after the connection is re-established.

 有两种类型的RowSet 

    Connected连接的RowSet对象本质上是永久性的。在应用程序终止之前,它不会终止。 

    Disconnected断开连接的RowSet对象本质上是临时的。只要它需要从数据库中检索数据,它就会建立连接并在完成所需任务后将其关闭。在重新建立连接后,将更新在断开连接状态期间修改的数据。

What is a "dirty read"?

In typical database transactions, say one transaction reads and changes the value while the second transaction reads the value before committing or rolling back by the first transaction. This reading process is called as 'dirty read'. Because there is always a chance that the first transaction might rollback the change which causes the second transaction reads an invalid value.

在典型的数据库事务中,假设一个事务读取并更改值,而第二个事务在第一个事务提交或回滚之前读取值。此读取过程称为“脏读”。因为第一个事务总是有可能回滚导致第二个事务读取的值无效。

Which isolation level prevents dirty read in JDBC, connection class?

TRANSACTION_READ_COMMITTED prevents dirty reads.

事务的读提交可以阻止脏读。

What is Metadata and why should you use it ?

JDBC API has two Metadata interfaces DatabaseMetaData & ResultSetMetaData. The meta data provides comprehensive information about the database as a whole. The implementation for these interfaces is implemented by database driver vendors to let users know the capabilities of a Database.

 JDBC API有两个Metadata接口DatabaseMetaData和ResultSetMetaData。元数据提供有关整个数据库的全面信息。这些接口的实现由数据库驱动程序供应商实现,以使用户了解数据库的功能。

How to Connect to an Excel Spreadsheet using JDBC int Java?

Follow the steps below

First setup the new ODBC datasource. Goto Administrative Tools−>Data Sources (ODBC)−>System DSN tab−>Add−>Driver do Microsoft Excel(*.xls)−>Finish. Now give the Data Source Name (SampleExcel) & Description. Next, click Select Workbook and point to your excel sheet.

In the code make to following code additions

按照以下步骤

首先设置新的ODBC数据源。转到管理工具 - >数据源(ODBC) - >系统DSN选项卡 - >添加 - >驱动程序执行Microsoft Excel(*。xls) - >完成。现在给出数据源名称(SampleExcel)和描述。接下来,单击“选择工作簿”并指向Excel工作表。 

在代码中添加以下代码

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbcodbcSampleExcel","","");
stmt = conn.createStatement();
sql = "select * from [Sheet1$]";
rs=stmt.executeQuery(sql);

What is difference between JDBC,JNDI and Hibernate?

  • Hibernate is an Object−Relational Mapping tool. It maps Objects to relational data.

  • The Java Naming and Directory Interface (JNDI) is an API to access different naming and directory services. You use it to access something stored in a directory or naming service without haveing to code specifically to that naming or directory service.

  • Java DataBase Connectivity (JDBC) API is an API to access different relational databases. You use it to access relational databases without embedding a dependency on a specific database type in your code.

    Hibernate是一个对象关系映射工具。它将对象映射到关系数据。 

    Java命名和目录接口(JNDI)是一种访问不同命名和目录服务的API。您可以使用它来访问存储在目录或命名服务中的内容,而无需专门为该命名或目录服务编写代码。 

    Java DataBase Connectivity(JDBC)API是一种用于访问不同关系数据库的API。您可以使用它来访问关系数据库,而无需在代码中嵌入对特定数据库类型的依赖关系。

猜你喜欢

转载自blog.csdn.net/successA/article/details/85053006