JDBC study (review) - detailed interview summary

1. Detailed introduction of JDBC

Reference link: JDBC detailed solution (many examples)

insert image description here

Two, jdbc interview summary

2.1 Steps for JDBC to operate the database?

  1. Register the database driver.
  2. Establish a database connection.
  3. Create a Statement.
  4. Execute SQL statements.
  5. Process the result set.
  6. The code to close the database connection
    is as follows:
Connection connection = null;
       Statement statement = null;
       ResultSet resultSet = null;
       try {
           /*加载驱动有两种方式:
            * 1:会导致驱动会注册两次,过度依赖于mysql的api,脱离的mysql的开发包,程序则无法编译
            * 2:驱动只会加载一次,不需要依赖具体的驱动,灵活性高
            *我们一般都是使用第二种方式
            * */
           //1.
           //DriverManager.registerDriver(new com.mysql.jdbc.Driver());
           //2.
           Class.forName("com.mysql.jdbc.Driver");
           //获取与数据库连接的对象-Connetcion
           connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/zhongfucheng", "root", "root");
           //获取执行sql语句的statement对象
           statement = connection.createStatement();
           //执行sql语句,拿到结果集
           resultSet = statement.executeQuery("SELECT * FROM users");
           //遍历结果集,得到数据
           while (resultSet.next()) {
               System.out.println(resultSet.getString(1));
               System.out.println(resultSet.getString(2));
           }
       } catch (SQLException e) {
           e.printStackTrace();
       } catch (ClassNotFoundException e) {
           e.printStackTrace();
       } finally {
           /*关闭资源,后调用的先关闭
            * 关闭之前,要判断对象是否存在
            * */
           if (resultSet != null) {
               try {
                   resultSet.close();
               } catch (SQLException e) {
                   e.printStackTrace();
               }
           }
           if (statement != null) {
               try {
                   statement.close();
               } catch (SQLException e) {
                   e.printStackTrace();
               }
           }
           if (connection != null) {
               try {
                   connection.close();
               } catch (SQLException e) {
                   e.printStackTrace();
               }
           }
       }

2.2 What is the difference between Statement, PreparedStatement and CallableStatement in JDBC?

the difference:

  • PreparedStatement: It is a precompiled SQL statement, which is more efficient than Statement.
  • PreparedStatement: supports operators and is more flexible than Statement.
  • PreparedStatement: It can prevent SQL injection and is more secure than Statement.
  • CallableStatement: Suitable for executing stored procedures.

2.3 Paging solution for large amount of data in JDBC?

 The best way is to use sql statements for pagination, so that the result set of each query only contains the data content of a certain page.

mysql syntax:
1
oracle syntax:
2

2.4 Talk about the working principle and implementation of the database connection pool?

2.4.1 Working principle

  When the JAVA EE server starts, it will establish a certain number of pool connections, and maintain no less than this number of pool connections. When a client program needs a connection, the pool driver returns an unused pool connection and marks it as busy. If there is no idle connection at present, the pool driver will create a certain number of connections, and the number of new connections is determined by configuration parameters. When the used pool connection call completes, the pool driver marks the connection as free so that other calls can use the connection.

2.4.2 Implementation plan

  The connection pool uses a collection to load, and the returned Connection is the proxy of the original Connection, the close method of the proxy Connection. When the close method is called, it does not actually close the connection, but puts the Connection object it proxies back into the connection pool and waits. Reuse next time.

code show as below:
3

2.5 How to handle transactions in Java?

  A transaction is a sequence of operations performed as a single logical unit of work. A logical unit of work must have four properties (ACID), called atomicity, consistency, isolation, and durability, only in this way can it become a transaction.
Four transaction processing methods are provided in the Connection class:

  • setAutoCommit(Boolean autoCommit): Set whether to automatically commit the transaction, the default is to automatically commit, which is true, and set false to prohibit the automatic commit of the transaction;
  • commit(): Commit the transaction;
  • rollback(): rollback transaction.
  • savepoint: save point
    Note: savepoint will not end the current transaction, normal commit and rollback will end the current transaction

2.6 Modify JDBC code quality

 The following program is a simple JDBC-based database access code, which implements the following functions: query all records in the product table from the database, and then print the output to the console. The code is of low quality, if the exception is not handled correctly, the connection Strings exist directly in the code in the form of "magic numbers". Please use your ideas to rewrite the program to complete the same function and improve the code quality.

Code before modification:
4

Modified points:
1. The url, password and other information should not be directly "written" with strings, but constants can be used instead. 2. The
transaction should be rolled back in the catch. Throwing RuntimeException is also a way to roll back the transaction.
3. Close resources

Modified code:5
6

2.7 Write a piece of code for JDBC to connect to the local MySQL database

7

2.8 How does JDBC realize the loose coupling between Java programs and JDBC drivers?

 Through the formulation of the interface, the database manufacturer will realize it. We just need to call through the interface. Just look at a simple JDBC example, you will find that all operations are done through the JDBC interface, and the driver will only appear when it is loaded through the Class.forName reflection mechanism.

2.9 What is the difference between execute, executeQuery, and executeUpdate?

  1. execute :
     The execute(String query) method of Statement is used to execute any SQL query. If the result of the query is a ResultSet, this method returns true. If the result is not a ResultSet, such as an insert or update query, it will return false. We can get the ResultSet through its getResultSet method, or get the number of updated records through the getUpdateCount() method.
  2. executeQuery :
     The executeQuery(String query) interface of Statement is used to execute select query and return ResultSet. Even if no record is found, the returned ResultSet will not be null. We usually use executeQuery to execute query statements. In this way, if an insert or update statement is passed in, it will throw a java.util.SQLException with the error message "executeQuery method can not be used for update".
  3. executeUpdate :
     The executeUpdate(String query) method of Statement is used to execute insert or update/delete (DML) statements, or return nothing to DDL statements. The return value is int type, if it is a DML statement, it is the number of updates, if it is a DDL statement, it returns 0.

Note: The execute() method should be used only when you are not sure what the statement is, otherwise the executeQuery or executeUpdate method should be used.

2.10 What are the disadvantages of PreparedStatement, and how to solve this problem?

One disadvantage of PreparedStatement is that we cannot use it directly to execute in conditional statements; if you need to execute IN conditional statements, here are some solutions:

  • Separate individual queries - this is poor performance and not recommended.
  • Use stored procedures - this depends on the database implementation, not all databases support it.
  • Dynamically generate PreparedStatement - this is a good way, but you can't enjoy the benefits of PreparedStatement cache. Use NULL values ​​in PreparedStatement queries - this is a good idea if you know the maximum number of input variables, and can be extended to support unlimited parameters.

2.11 What is the dirty read of JDBC? Which database isolation level prevents dirty reads?

Dirty read: One transaction reads uncommitted data from another transaction

Example: A transfers money to B, A executes the transfer statement, but A has not submitted the transaction, B reads the data and finds that the money in his account has increased! B told A that I have received the money. A rolls back the transaction [rollback], and when B checks the money in the account again, he finds that there is not much money.

The following three isolation levels can prevent:

  • Read commit: Read committed【TRANSACTION_READ_COMMITTED】
  • Repeatable read: Repeatable read [TRANSACTION_REPEATABLE_READ]
  • Serialization: Serializable [TRANSACTION_SERIALIZABLE]

2.12. What is a phantom read and which isolation level can prevent it?

Phantom reading refers to the reading of data inserted by other transactions in one transaction, resulting in inconsistency in reading before and after.
Only the serialization (TRANSACTION_SERIALIZABLE) isolation level can prevent phantom reads.

2.13 What is the DriverManager of JDBC used for?

 JDBC's DriverManager is a factory class through which we create database connections. When the JDBC Driver class is loaded, it will register itself in the DriverManager class. Then we will pass the database configuration information to the DriverManager.getConnection() method, and the DriverManager will use the driver registered in it to obtain the database connection and return it to the calling program.

2.14 ResultSet

2.14.1 What is the ResultSet of JDBC?

After querying the database, a ResultSet will be returned, which is like a data table of the query result set.
 The ResultSet object maintains a cursor pointing to the current row of data. At the beginning, the cursor points to the first row. If the ResultSet's next() method is called, the cursor will move down one row. If there is no more data, the next() method will return false. It can be used in a for loop to iterate through the dataset.
 The default ResultSet cannot be updated, and the cursor can only be moved down. That is to say, you can only traverse from the first line to the last line. However, you can also create a ResultSet that can be rolled back or updated.
When the Statement object that generates the ResultSet is to be closed or re-executed or to obtain the next ResultSet, the ResultSet object will also be automatically closed.
 The column data can be obtained by passing in the column name or the serial number starting from 1 through the getter method of ResultSet.

2.14.2 What are the different ResultSets?

 Depending on the input parameters when creating a Statement, it will correspond to different types of ResultSet. If you look at the methods of Connection, you will find that the createStatement and prepareStatement methods are overloaded to support different ResultSet and concurrency types.
 There are three ResultSet objects.

  1. ResultSet.TYPE_FORWARD_ONLY: This is the default type, its cursor can only move down.
  2. ResultSet.TYPE_SCROLL_INSENSITIVE: The cursor can move up and down. Once it is created, the data in the database is modified again, which is transparent to it.
  3. ResultSet.TYPE_SCROLL_SENSITIVE: The cursor can move up and down. If the database is modified after it is generated, it can be perceived.

 ResultSet has two types of concurrency.

  • ResultSet.CONCUR_READ_ONLY: ResultSet is read-only, which is the default type.
  • ResultSet.CONCUR_UPDATABLE: We can use the update method of ResultSet to update the data inside.

2.15 What is JDBC's DataSource and what are its benefits?

 DataSource is the data source. It is an interface defined in javax.sql. Compared with DriverManager, its function is more powerful. We can use it to create a database connection, and of course the driver implementation class will actually do the work. In addition to being able to create connections, it also provides the following features:

  1. Cache PreparedStatement for faster execution
  2. You can set the connection timeout
  3. Provide logging functionality
  4. Maximum threshold setting for ResultSet size
  5. Through the support of JNDI, the function of connection pool can be provided for the servlet container

2.16 What are the common JDBC exceptions?

There are the following:

  • java.sql.SQLException: This is the base class for JDBC exceptions.
  • java.sql.BatchUpdateException: This exception may be thrown when a batch operation fails to execute. It depends on the implementation of the specific JDBC driver, it may also directly throw the base class exception java.sql.SQLException.
  • java.sql.SQLWarning: SQL operation warning information.
  • java.sql.DataTruncation: The field value was truncated for some unusual reason (not because it exceeded the length limit of the corresponding field type).

Question 1: What is SQLWarning, and how to get SQLWarning in the program?
  SQLWarning is a subclass of SQLException, which can be obtained through the getWarnings methods of Connection, Statement, and Result. SQLWarning will not interrupt the execution of the query statement, but is only used to prompt the user to have relevant warning information.

What to do if java.sql.SQLException: No suitable driver found?
  This exception will be thrown if your SQL URL string is malformed. Whether using DriverManager or JNDI data source to create a connection may throw this exception. Its exception stack will look like the following.
2
The way to solve this kind of problem is to check the log file, like the log above, the URL string is 'jdbc:mysql://localhost:3306/UserDB, just change it to jdbc:mysql://localhost:3306 /UserDB is fine.

2.17 What is the RowSet of JDBC, and what are the different RowSets?

 RowSet is used to store the data results of the query, and it is more flexible than ResultSet. RowSet inherits from ResultSet, so what ResultSet can do, they can do, and what ResultSet can't do, they can still do. The RowSet interface is defined in the javax.sql package.
 Additional features provided by RowSet are:

  1. Provides the function of Java Bean, which can set and get properties through settter and getter methods. RowSet uses the event-driven model of JavaBean, which can send event notifications to registered components, such as cursor movement, row addition, deletion, and RowSet content modification.
  2. The RowSet object is scrollable and updatable by default, so if the database system does not support ResultSet to achieve similar functions, you can use RowSet to achieve it.
     RowSet is divided into two categories:
  • Connection type RowSet: This type of object is connected to the database, which is very similar to ResultSet. The JDBC interface only provides a connection type RowSet, javax.sql.rowset.JdbcRowSet, and its standard implementation is com.sun.rowset.JdbcRowSetImpl.
  • Offline RowSet: These objects do not need to be connected to the database, so they are lighter and easier to serialize. They are suitable for passing data between networks.
     There are four different offline RowSet implementations.
  • CachedRowSet: You can get connections through them, execute queries and read ResultSet data into RowSet. We can maintain and update the data offline, then reconnect to the database and write back the changed data.
  • WebRowSet: inherited from CachedRowSet, he can read and write XML documents.
  • JoinRowSet: Inherited from WebRowSet, it can perform SQL join operations without connecting to the database.
  • FilteredRowSet: Inherited from WebRowSe, we can use it to set filtering rules so that only the selected data is visible.

2.18 What are the different types of locks in JDBC?

Broadly speaking, there are two locking mechanisms to prevent data corruption caused by simultaneous operations by multiple users.

  1. Optimistic locking: records are locked only when data is updated.
  2. Pessimistic locking: Data records are locked during the entire process from query to update and submission.

2.19 What is the best practice of JDBC?

  1. Database resources are very expensive and should be closed as soon as they are used up. JDBC objects such as Connection, Statement, and ResultSet all have a close method, just call it.
  2. Develop the habit of explicitly closing ResultSet, Statement, and Connection in the code. If you use a connection pool, the connection will be put back into the pool after use up, but the ResultSet and Statement that are not closed will cause resource leaks.
  3. Close the resource in the finally block to ensure that it can be closed normally even if an exception occurs.
  4. Large numbers of similar queries should be done using batch processing.
  5. Try to use PreparedStatement instead of Statement to avoid SQL injection, and improve execution efficiency through precompilation and caching mechanisms.
  6. If you want to read a large amount of data into ResultSet, you should set fetchSize reasonably to improve performance.
  7. The database you use may not support all isolation levels, please check carefully before using it.
  8. The higher the database isolation level, the worse the performance. Make sure that the isolation level set for your database connection is optimal.
  9. If you create a database connection in a WEB program, it is best to use the JDBC data source through JNDI, so that the connection can be reused.
  10. If you need to operate on ResultSet for a long time, try to use offline RowSet.

Guess you like

Origin blog.csdn.net/weixin_44462773/article/details/129201537