`
kylinsoong
  • 浏览: 236320 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Thinking in JDBC

阅读更多

This blog will beas on a series of examples to account for each viewpoint which will list below.

I. Overview of JDBC

      JDBC defines how a Java program can communicate with a database. JDBC API provides two packages they are java.sql and javax.sql . By using JDBC API, you can connect virtually any database, send SQL queries to the database and process the results. JDBC API provides interfaces and classes to work with databases. Connection interface encapsulates database connection functionality, Statement interface encapsulates SQL query representation and execution functionality and ResultSet interface encapsulates retrieving data which comes from execution of SQL query using Statement. The following are the basic steps to write a JDBC program:

      1. Import java.sql and javax.sql packages
      2. Load JDBC driver
      3. Establish connection to the database using Connection interface
      4. Create a Statement by passing SQL query
      5. Execute the Statement
      6. Retrieve results by using ResultSet interface
      7. Close Statement and Connection

Code Demo:

public class JDBCTest {

	public static void main(String[] args) throws SQLException {
		Connection conn = null;
		Statement stmt = null;
		ResultSet r = null;
		final String driver = "oracle.jdbc.OracleDriver";
		final String url = "jdbc:oracle:thin:@//192.168.1.107:1521/oracl";
		final String user = "IPCUSER";
		final String passwd = "tibco";
		
		try {
			Class c = Class.forName(driver);
			Driver d = (Driver) c.newInstance();
			DriverManager.registerDriver(d);
			conn = DriverManager.getConnection(url, user, passwd);
			stmt = conn.createStatement();
			r = stmt.executeQuery("SELECT USER_TABLES.TABLE_NAME FROM USER_TABLES");
			while(r.next()) {
				System.out.println(r.getString(1));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			r.close();
			stmt.close();
			conn.close();
		}	
	}
}

 

 Demo Code will extrct all table name of current user

 

II. Does "Connection.setAutoCommit(false)" mean "begin a transaction?"

      A transaction is simply an operation that is irreversibly completed. By default, JDBC connections start in autocommit mode. This means that every executed statement is treated as a separate transaction. There are occasions where this default behavior is undesirable. Having every statement commited to the database can reduce performance. In addition, a set of statements may have dependencies such that previous statements should be undone if a succeeding statement fails. This is why the JDBC API provides the

Connection.setAutoCommit() method.

You can turn off the default autocommit behavior by calling this method with an argument of false.

All statements executed afterward will not take effect until you call commit().

Therefore, the first call of setAutoCommit(false), and each call of commit() implicitly mark the start of a transaction. Transactions can be undone before they are committed by calling rollback().  You will typically rollback a transaction when one of its constituent statements fails

 

III. ROWNUM Pseudocolumn

1. rownum is a pseudo column. It numbers the records in a result set. The first record that meets the where criteria in a select statement is given rownum=1, and every subsequent record meeting that same criteria increases rownum.

2. Conditions testing for ROWNUM values greater than a positive integer are always false. For example, this query returns no rows:

select * from migrationproclog where rownum > 1

The first row fetched is assigned a ROWNUM of 1 and makes the condition false. The second row to be fetched is now the first row and is also assigned a ROWNUM of 1 and makes the condition false. All rows subsequently fail to satisfy the condition, so no rows are returned.

 

IV. Query with index is 50 times faster than witout index

      I will give a test statistic to demostrate this viewpoint. In this test there are more then 1 000 000 data exists in table ORDERS, I have query the 1 000 000th row two times, the first time without index in num column, and the second times create index in num column, as following:

Query SQL Statement:

SELECT num, extract(data, '/') FROM ORDERS WHERE num = 1000000

Create Index Statement:

create index orders_num_index on orders(num);

Query Time:

without index Time: 178953 milliseconds
     with index Time: 3297 milliseconds

 

 So if our application need query database frequently we should consider create index to ehance query performance. 

 

V. Use pseudo ROWNUM to implement Pagination should be careful

      It's really frequent that we need to page query, for example the following demo show query Orders rows from 1 000 000 to 1 500 000, usually we can achieve this goal through rownum, I will give my Pagination SQL statement and the query time directly:

SELECT r, target FROM (SELECT ROWNUM r, extract(data, '/') target FROM orders ) WHERE r >= 1 AND r < 500000
Time: 218 milliseconds
SELECT r, target FROM (SELECT ROWNUM r, extract(data, '/') target FROM orders ) WHERE r >= 500000 AND r < 1000000
Time: 513610 milliseconds
SELECT r, target FROM (SELECT ROWNUM r, extract(data, '/') target FROM orders ) WHERE r >= 1000000 AND r < 1500000
Time: 1429547 milliseconds

 

SELECT r, extract(data, '/') FROM (SELECT ROWNUM r, data FROM orders ) WHERE r >= 1 AND r < 500000
Time: 235 milliseconds 
SELECT r, extract(data, '/') FROM (SELECT ROWNUM r, data FROM orders ) WHERE r >= 500000 AND r < 1000000
Time: 79578 milliseconds
SELECT r, extract(data, '/') FROM (SELECT ROWNUM r, data FROM orders ) WHERE r >= 1000000 AND r < 1500000
Time: 130015 milliseconds

 

SELECT r, extract(data, '/') FROM (SELECT ROWNUM r, data FROM orders WHERE ROWNUM < 500000) WHERE r >= 1
Time: 203 milliseconds
SELECT r, extract(data, '/') FROM (SELECT ROWNUM r, data FROM orders WHERE ROWNUM < 1000000) WHERE r >= 500000
Time: 73204 milliseconds
SELECT r, extract(data, '/') FROM (SELECT ROWNUM r, data FROM orders WHERE ROWNUM < 1500000) WHERE r >= 1000000
Time: 124391 milliseconds

 

The above sql statement illustrate 3 different pagination methods and the query time is very different, so we should be careful when we use ROWNUM to implement Pagination .

 

1
0
分享到:
评论

相关推荐

    Thinking in Java简体中文(全)

    15.7.3 JDBC API为何如何复杂 15.8 远程方法 15.8.1 远程接口概念 15.8.2 远程接口的实施 15.8.3 创建根与干 15.8.4 使用远程对象 15.8.5 RMI的替选方案 15.9 总结 15.10 练习 第16章 设计范式 16.1 范式的概念 ...

    Thinking in Java 中文第四版+习题答案

    15.7.3 JDBC API为何如何复杂 15.8 远程方法 15.8.1 远程接口概念 15.8.2 远程接口的实施 15.8.3 创建根与干 15.8.4 使用远程对象 15.8.5 RMI的替选方案 15.9 总结 15.10 练习 第16章 设计范式 16.1 范式的概念 ...

    JAVA_Thinking in Java

    15.7.3 JDBC API为何如何复杂 15.8 远程方法 15.8.1 远程接口概念 15.8.2 远程接口的实施 15.8.3 创建根与干 15.8.4 使用远程对象 15.8.5 RMI的替选方案 15.9 总结 15.10 练习 第16章 设计范式 16.1 范式的概念 ...

    JAVA_Thinking in Java(中文版 由yyc,spirit整理).chm

    JAVA_Thinking in Java(中文版 由yyc,spirit整理).chm ------------------------------------------------- 本教程由yyc,spirit整理 ------------------------------------------------- “Thinking in Java...

    Thinking in Java(中文版 由yyc,spirit整理).chm

    “Thinking in Java”详细目录   写在前面的话 引言 1. 前提 2. Java的学习 3. 目标 4. 联机文档 5. 章节 6. 练习 7. 多媒体CD-ROM 8. 源代码 9. 编码样式 10. Java版本 11. 课程和培训 12. 错误 13. 封面设计 ...

    Java学习书目(各学习阶段都有推荐)

    《Thinking in Java》- 强烈推荐* O’reilly的Java编程基础系列 - 参考* 二、进阶 《Java Cook Book》- 非常推荐* (包含了Java编程的Tips,适合当做手册来查阅) 《O’reilly-Java IO》- 推荐* (包含Java IO...

    Mahout in Action

    preliminary thinking 246 ■ Choosing a learning algorithm to train the model 247 ■ Improving performance of the color-fill classifier 250 13.6 Summary 254 14 Training a classifier 255 14.1 Extracting...

    java8集合源码分析-thinking-in-spring:小马哥极客时间Spring编程思想示例项目

    JDBC 事务抽象(Transactions) DAO 支持(DAO Support) O/R映射(O/R Mapping) XML 编列(XML Marshalling) Web 技术(Web) Web Servlet 技术栈 Spring MVC WebSocket SockJS Web Reactive 技术栈 Spring WebFlux ...

    java初学者的工具ppt文件

    但无论如何,《Thinking In Java》绝对不应该作为你入门Java的第一本书籍! 记住,网络上学习Java的资源很多,但基本不够系统,拥有一本Java入门书籍,是你系统学习Java的基础。 2)准备Java学习环境。 准备你的学习...

    二十三种设计模式【PDF版】

    使用类再生的两个方式:组合(new)和继承(extends),这个已经在 thinking in java中提到过. 设计模式之 Proxy(代理) 以 Jive 为例,剖析代理模式在用户级别授权机制上的应用 设计模式之 Facade(门面?) 可扩展的使用...

Global site tag (gtag.js) - Google Analytics