JDBC-Interview Questions翻譯

ZeroWM發表於2018-12-18

原文: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。您可以使用它來訪問關聯式資料庫,而無需在程式碼中嵌入對特定資料庫型別的依賴關係。

 

 

相關文章