Java interview 4.11 Java database operations - Java programmers written interview Collection

4.11.1 how to access the database via JDBC

Java Database Connectivity (Java DataBase Connectivity, JDBC) used to implement database operations function in a Java program, which provides the execution of SQL statements, methods to access a variety of databases, and provide a unified user interface for a variety of different databases, java. sql package contains all the JDBC-database operation. JDBC database accessed by a general has the following steps:

1) load JDBC driver. The JDBC driver database is loaded into the classpath, based on JavaEE Web application development process, usually make the target database products JDBC Driver copied to the WEB-INF / lib.

2) loading the JDBC driver, and registered with the DriverManager. Usually a reflective Class.forName (String driveName).

3) establish a database connection, obtain a Connection object. Typically by DriverManager.getConnection (url, username, passwd) implemented method, wherein, url string represents a connection to the database, the user name username database connection, a database connection code represents the passwd.

4) establishment of PreparedStatement Statement object or objects.

5) execute SQL statements.

6) to access the result set ResultSet object.

7) turn ResultSet, Statement, PreparedStatement, Connection object is closed, occupied freed resources, such as rs.close (), con.close () and so on. Why do you do that? The reason is that most often accomplished JDBC driver SQL commands and data transmitted through the network IO at the bottom.

3. To provide Java database access capability package is ().

A.java.sql B.java.awt C.java.lang D.java.swing

The answer: A. Database operations for all classes in the java.sql package.


4.11.2 JDBC transaction processing what method

A transaction is an indivisible unit of work from one or more SQL statements to the database operations consisting only when all operations in the transaction are executed properly finished, the entire transaction will be submitted to the database. In JDBC, typically through to end the transaction commit () method or rollback () method of operation. Wherein the commit () method to indicate the completion of the transaction is submitted, ROLLBACK () method of indicating the completion of the transaction is rolled back, and more for the case where an abnormality occurred during the processing of a transaction, these two methods are in java.sql.Connection class. In general, the default action is to automatically submit the transaction, ie after the operation is successful, the system will automatically call commit () method, otherwise it calls the rollback () method.

Of course, JDBC, but also can be disabled by calling setAutoCommit (false) method automatically submit, then you can put the expression of multiple database operations as a transaction, call commit after the operation is complete () method to achieve the overall submission, if one an expression operation fails, it will throw an exception without calling commit () method. In this case, you can call rollback () method in the code block abnormal captured transaction for rollback. After multiple operations on the database can be maintained by this method, the data remains consistent.

Extended: JDBC What transaction isolation level?

In order to solve the "multiple threads request the same data" related problems, often with the transaction between the lock to open isolated from each other. Today, most major databases support different types of locks. Thus, JDBC API to support different types of transactions, which is assigned or determined by the Connection object. In JDBC, we define the following five kinds of transaction isolation levels:

1) TRANSACTION_NONE JDB. It does not support transactions.

2) TRANSACTION_READ_UNCOMMITTED. Uncommitted read. Description A transaction may see a change in another transaction before submitting. Such read "dirty" data, non-repeatable reads and phantom reads are allowed.

3) TRANSACTION_READ_COMMITTED. Read Committed. Description data read uncommitted is not allowed. This level still allows non-repeatable reads and phantom reads generated.

4) TRANSACTION_REPEATABLE_READ. Repeatable read. Description affairs to ensure that the same data can be read again without fail, but phantom reads still occur.

5) TRANSACTION_SERIALIZABLE. Serializable. Is the highest transaction level that prevents read "dirty" data, non-repeatable reads and phantom reads.

(Note:. ① read "dirty" data in a transaction data has been read another transaction has not yet submitted, for example, when a transaction A and B transactions execute concurrently, updated when Transaction A Transaction B to A query read yet data, this time a roll back the transaction, the transaction data B is invalid read "dirty" data .② non-repeatable reads. causes a transaction before and after operation of another transaction to read two different data, e.g., when the transaction a and B concurrently executing transactions, transaction B when reading data query, update transaction a transaction B changes to query the data, then transaction B again to read the data and found that twice before and after the data is not the same. ③ dummy read operation in a transaction resulting in different amounts of data twice before and after results of another transaction query, for example, when a transaction a transaction B concurrently, when reading the data query transaction B, add or delete a transaction a a meet record a query of the transaction, in which case, transaction B again query, the query to find the previous records do not exist, or a previous record was gone.)

The higher the transaction isolation level, in order to avoid conflicts of energy spent on the more. Isolation level can be set by conn.setTransactionLevel () method of the Connection object, determined by the level of the current transaction conn.getTransactionIsolation () method.


What is the role of 4.11.3 Class.forName

In the Java language, any class only to be loaded onto the JVM to run. Effect the Class.forName () method of the class is loaded into the JVM, and it will return a Class object class or interface associated with a given string name of the class is loaded and the JVM, the JVM executes the same time static code segment class.

Before using JDBC connection to the database, usually calling Class.forName ( "com.mysql.jdbc.Driver") method to load the JDBC driver, you need to call certain whether this approach? If so, why call this approach? In fact, this method does not have to call, for example, Test t = (Test) Class.forName ( "Test"). NewInstance () statements and Test t = new Test () statement would have the same effect, so the use of new It can be, but the difference between the two is very clear: to create objects in different ways. The former uses class loading mechanism, which is to create a new class. The first method tends to increase the scalability of the software, for example, after a software development project will be a number of companies to use each company's process flow is substantially the same, only the individual company's business logic is different in the development process which I could have no common place to be extracted is defined as an interface BussinessInterface, implementation class sub1 define different for each company's different business processes, sub2, sub3, etc., to accomplish different business needs by creating different subclasses. To achieve good scalability, can be arranged using handle class file into an XML file. When deployed, just from reading the configuration file to read the class name className, then using BussinessInterface b = (BussinessInterface) Class.forName (className) .newInstance () to create an instance of improving developer productivity. When later there are new needs, even developed a new subclass does not need to modify the code that creates an instance, only need to modify configuration files, so that the program has good scalability.


4.11.4 Statement, PreparedStatement and CallableStatement What is the difference

3)安全性更好。使用 PreparedStatement 能够预防 SQL 注入攻击,所谓 SQL 注入,指的是通过把 SQL 命令插入到 Web 表单递交或输入域名或页面请求的查询字符串,最终达到欺骗服务器,达到执行恶意 SQL 命令的目的。注入只对 SQL 语句的编译过程有破坏作用,而执行阶段只是把输入串作为数据处理,不再需要对 SQL 语句进行解析,因此也就避免了类似 select∗from user where name=′aa′and password=′bb′or 1=1 的 SQL 注入问题的发生。

CallableStatement 由 prepareCall()方法所创建,它为所有 DBMS(Database Management Sys-tem,数据库管理系统)提供了一种以标准形式调用已储存过程的方法。它从 PreparedStatement 中继承了用于处理输入参数的方法,而且还增加了调用数据库中的存储过程和函数以及设置输出类型参数的功能。

常见笔试题:

用于调用存储过程的对象是( )。

A.ResultSet B.DriverManager C.CallableStatemet D.PreparedStatement

答案:C。JDBC 中的 CallableStatement 对象为所有 RDBMS(Relational Database Management System,关系数据库管理系统)提供了一种标准形式调用存储过程的方法。其对存储过程的调用存在两种形式:带结果参数和不带结果参数。结果参数是一种输出参数,是存储过程的返回值。两种形式都可带有数量可变的输入(IN 参数)、输出(OUT 参数)或输入和输出(IN-OUT 参数)的参数。


4.11.5 getString()方法与 getObject()方法有什么区别

JDBC 提供了 getString()、getInt()和 getData()等方法从 ResultSet 中获取数据,当查询结果集中的数据量较小时,不用考虑性能,使用这些方法完全能够满足需求,但是当查询结果集中的数据量非常大时,则会抛出异常:OracleException 未处理:ORA-01000:maximum open cursors exceeded(以访问 Oracle 数据库为例)。而通常情况下,使用 getObject()方法就可以解决这个问题。

getString()或 getInt()等方法在被调用时,程序会一次性地把数据都放到内存中,然后通过调用 ResultSet 的 next()和 getString()等方法来获取数据。当数据量大到内存中放不下时就会抛出异常,而使用 getObject()方法就不会这种问题,因为数据不会一次性被读到内存中,每次调用时会直接从数据库中去获取数据,因此使用这种方法不会因为数据量过大而出错。


4.11.6 使用 JDBC 时需要注意哪些问题

在使用 JDBC 编程时,首先需要建立于数据库的连接,才能完成对数据库的访问,由于与数据库的连接是非常重要的资源。JDBC 连接池提供了 JDBC 连接定义和数目有限的连接,如果连接数量不够,就需要长时间的等待。不正常关闭 JDBC 连接会导致等待回收无效的 JDBC 连接。只有正常的关闭和释放 JDBC 连接,JDBC 资源才可以被快速地重用,从而使得系统性能得到改善。因此在编程时,一定要保证释放不再使用的连接。

一般来讲,在使用 JDBC 访问数据库时,createStatement 和 prepareStatement 最好放在循环外面,而且使用了这些 Statement 后,需要及时关闭。最好是在执行了一次 executeQuery、exe-cuteUpdate 等之后,如果不需要使用结果集(ResultSet)的数据,就马上将 Statment 关闭。因为每次执行 conn.createStatement()或 conn.prepareStatement(),实际上都相当于在数据库中打开了一个 cursor(游标),如果把对这两个方法的调用放到循环内,会一直不停地打开 cursor。如果不能及时地关闭,会导致程序抛出异常。


4.11.7 什么是 JDO

Java 数据对象(Java Data Object,JDO)是一个用于存取某种数据仓库中的对象的标准化 API,它使开发人员能够间接地访问数据库。

JDO 是 JDBC 的一个补充,它提供了透明的对象存储,因此对开发人员来说,存储数据对象完全不需要额外的代码(例如 JDBC API 的使用)。这些烦琐的工作已经转移到 JDO 产品提供商身上,使开发人员解脱出来,从而集中时间和精力在业务逻辑上。另外,相较于 JDBC,JDO 更灵活、更通用,它提供了到任何数据底层的存储功能,例如关系数据库、文件、XML 以及对象数据库管理系统(Object Database Management System,ODBMS)等,使得应用可移植性更强。


4.11.8 JDBC 与 Hibernate 有什么区别

Hibernate 是 JDBC 的封装,采用配置文件的形式将数据库的连接参数写到 XML 文件中,至于对数据库的访问还是通过 JDBC 来完成的。

Hibernate 是一个持久层框架,它将表的信息映射到 XML 文件中,再从 XML 文件映射到相应的持久化类中,这样可以使用 Hibernate 独特的查询语言 Hibernate 查询语言(Hibernate Que-ry Language,HQL)了。Hibernate 的 HQL 查询语句返回的是 List<Object[.]> 类,而 JDBC 通过 statement 返回的查询结果是 ResultSet 并且有时候需要自己封装到 List 中。另外一个重要区别在于,Hibernate 具有访问层(DAO 类层,DAO 全称为 Data Access Object 数据访问接口,意为数据访问接口),该层是 HQL 查询语句唯一出现的位置,再往上层则不会出现查询语句,而 JDBC 可以随时连接随时访问,例如有 100 个类都有 SQL 查询语句,如果表名改变了,那么要使用 JDBC 的方式,就必须重写所有查询语句,而采用 Hibernate 的方式只需修改 DAO 层的类即可,因此 Hibernate 具有很好的维护性和扩展性。

发布了101 篇原创文章 · 获赞 20 · 访问量 6万+

Guess you like

Origin blog.csdn.net/qq_40993412/article/details/104065173