01: Always get connection from Connection pool
Examples
import java.io.*;
public static void main(String[] arg)
{
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("jdbc/eBBS");
Connection con = ds.getConnection();
}
Rationale
Use Connection pool to get connection instead of DriverManager.getConeection .Since it is already having connections in pool, so it will take less time to get connection.
02: Always use Prepared statement instead of statement for executing Regular SQL queries (Not Dynamic Queries)
Examples
PreparedStatement st = con.prepareStatement(str_SQL);
Rationale
Prepared statements are precompiled statements and faster .It will create the execution package in DB level and reuse the same package when the same query executed multiple times.
03: Close All Connections, PreparedStatements, and Resultsets immediately once Execution /operations completes.
Examples
finally {
try {
if (resultset != null)
resultset.close();
if (preparestatement != null)
preparestatement.close();
if (connection != null)
connection.close();
} catch (SQLException e) {
throw new ApplicationException("SYS", "1000", e.getMessage()) }
Rationale
All Connections, Preparedstatements, Resultsets need to be close once the execution completes. Always Close Resultset first, then Prepared statements and Connections once the operation completes and also in Finally block at the end. This will avoid memory related issues and avoid Connection leakage related issues
04: Always specify a column list with in select/insert/Update/Delete SQL statements
Examples
String sqlQuery = "SELECT COUNTRYCODE, NAME, RISK FROM CNTRY "
Rationale
Always specify required column list with in select/insert/update/Delete statements (avoid "select *").
05:Use Isolation level appropriately
Examples
con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED)
Rationale
Use the isolation level appropriately based on operations requirements. i.e. , if the Database connection requires operating only Selection operation then use Isolation level for only reading the values from DB which will output good performance.
06: Handle SQL related specific exceptions
Examples
catch (SQLException e) {
throw new ApplicationException("SYS", "1000", e.getMessage())
}
Rationale
Always handle the SQL related specific exceptions logic during performing Database operations like SQLException, BatchUpdateException.This will helpful to Debug for any exceptions by using Error messages and Reason codes.
07: Use Batch update / Batch insert instead of insert/update for multiple rows of data in same time
Examples
import java.io.*;
public static void main(String[] arg)
{
Connection conn = ds.getConnection();
Statement statement = conn.createStatement();
String insertQuery1 = "INSERT INTO ACCOUNT VALUES(01,XXX,'C')";
statement.addBatch(insertQuery1);
String insertQuery2 = "INSERT INTO ACCOUNT VALUES(01,YYY,'D')";
statement.addBatch(insertQuery2);
statement.executeBatch();
}
Rationale
Always use Batch Update /Insert instead of single update/insert for multiple rows of data hits in same table at same time (especially during batch operations for insert & update) , this will avoid the multiple database hits and provide Good response. Also handle Batch Exception handling to proper debugging.
08: Always Use Optimized query and minimize the size of Result set
Examples
import java.io.*;
public static void main(String[] arg)
{
pstmt = con.prepareStatement("SELECT id,name, age FROM CustInfo WHERE age > 10 ");
rs = pstmt.executeQuery();
}
Rationale
Always use optimized query before applying in program (Get suggestion from DataBase experts for new /Complex SQL queries) and make sure the result set will fetch only required data only.
09: Use appropriate data types instead of using ”string ” for all the data types.
Examples
import java.io.*;
public static void main(String[] arg)
{
rs.getDate(1);
rs.getBigDecimal(2);
rs.getInt(3)
}
Rationale
Please use appropriate data types instead using “string” for all the data types. If DB column is BigDecimal and if you are fetching this value use getBigDecimal to store the value. Also Use Date, Time, Timestamp objects as host Variables fields instead of Strings.
10: If Collection object using in program to store database values Nullify the object once the operation completes
Examples
HashMap hm = new HashMap();
pstmt = con.prepareStatement(SELECT_SQL);
rs = pstmt.executeQuery();
id= rs.getBigDecimal(1);
name= rs.getString(2);
hm.put(id,name);
hm.clear();
Rationale
If any collections object - Vector/Hashmap using to store Resultset values, please nullify that collection object once the operation is over. This will avoid the memory leakage issue
11: Avoid using Dynamic SQL Queries
Examples
String SELECT_SQL = “select systemdate from db2inst1.system ";
SELECT_SQL1 = SELECT_SQL + "where systemdate=?”
Rationale
Always avoid usage of Dynamic SQL Queries, Dynamic queries will form based on
concatenation “+” operation and which will cause performance issue.
12: Limit the usage of Platform specific features in SQL
Examples
String SELECT_SQL = “select systemdate from db2inst1.Account Fetch first 10 rows only";
Rationale
Always try to avoid usage of platform specific commands, it means the Query which we have written should be compatible to run at any database like DB2/ORACLE.
13: Always Use Column Number instead of Column Name for get Methods in Result sets.
Examples
String sqlQuery = "SELECT COUNTRYCODE, NAME, RISK FROM CNTRY ";
When fetching values from Resultset -rs use as below to get countrycode value.
rs.getString(1); instead of rs.getString(“COUNTRYCODE”);
Rationale
Use Column Number instead of Column name in result set get methods to get value of the SQL columns.
14: Avoid to use PreparedStatements inside loops
Examples
SQL1 = "SELECT COUNTRYCODE, NAME, RISK FROM CNTRY "
SQL2 = "SELECT EMPID,EMPNAME,DESG FROM EMP "
While(rs.next())
{
PreparedStatement emp_ps = con.prepareStatement(SQL2);
---
---
}
Rationale
Always avoid to write / execute PreparedStatements inside loops which will cause performance issues.
15: Limit the usage of Column functions (Aggregate/Sum/Count) in SQL
Examples
"SELECT SUM(AMOUNT) FROM SAL ";
"SELECT COUNT(NAME) FROM EMP ";
Rationale
Always try to restrict usage of Column functions (Aggregate/Sum/Count) in queries to avoid Performance/Portability issues
16: Use Stored Procedures using JDBC
Examples
CREATE PROCEDURE DB2INST1.MOVE_TO_HIST_RETTRN()
BEGIN
DECLARE r_stmt VARCHAR(1500);
DECLARE h_stmt VARCHAR(2500);
SET r_stmt = 'insert INTO db2inst1.RETTRNHIST (BATCHNO,BATCHENTRYDATE,SEQNO,CURRENCYCODE,ACCOUNTNO)select BATCHNO,
BATCHENTRYDATE,SEQNO,CURRENCYCODE,ACCOUNTNO from db2inst1.RETTRN where batchentrydate < (SELECT PREVWORKINGDATE FROM DB2INST1.SYSTEM)';
PREPARE Q1 FROM r_stmt;
EXECUTE Q1;
SET h_stmt = 'DELETE FROM DB2INST1.RETTRN WHERE BATCHENTRYDATE <
(SELECT PREVWORKINGDATE FROM DB2INST1.SYSTEM)';
PREPARE Q2 FROM h_stmt;
EXECUTE Q2;
END
Rationale
Stored procedures are ideal when there is a complex piece of business logic that needs to be performed involving a lot of database access.
事务的隔离级别(5个):
ISOLATION_DEFAULT
ISOLATION_READ_UNCOMMITTED:会产生脏读,不可重复读和幻像读
ISOLATION_READ_COMMITTED:可以避免脏读出现,但是可能会出现不可重复读和幻像读
ISOLATION_REPEATABLE_READ:可以防止脏读,不可重复读。但是可能出现幻像读
ISOLATION_SERIALIZABLE:可以防止脏读,不可重复读外,还避免了幻像读
事务传播行为(7个):
PROPAGATION_REQUIRED :如果存在一个事务,则支持当前事务。如果没有事务则开启一个新的事务;PROPAGATION_REQUIRED:应该是我们首先的事务传播行为。它能够满足我们大多数的事务需求。
PROPAGATION_SUPPORTS :如果存在一个事务,支持当前事务。如果没有事务,则非事务的执行
PROPAGATION_MANDATORY :如果已经存在一个事务,支持当前事务。如果没有一个活动的事务,则抛出异常。
PROPAGATION_REQUIRES_NEW :总是开启一个新的事务。如果一个事务已经存在,则将这个存在的事务挂起。
PROPAGATION_NOT_SUPPORTED :总是非事务地执行,并挂起任何存在的事务。
PROPAGATION_NEVER :总是非事务地执行,如果存在一个活动事务,则抛出异常
PROPAGATION_NESTED :如果一个活动的事务存在,则运行在一个嵌套的事务中. 如果没有活动事务, 则按TransactionDefinition.PROPAGATION_REQUIRED 属性执行
相关推荐
"JAVA岗位开发指导培训视频"提供了一个全面的学习平台,由经验丰富的讲师授课,旨在帮助初学者和有经验的开发者提升技能,更好地适应Java开发岗位的需求。 在Java开发中,基础知识包括但不限于语法、面向对象编程...
Java编程开发指导主要涵盖以下几个核心知识点: 1. **Java基础知识**:Java是一种广泛使用的面向对象的编程语言,由Sun Microsystems(现为Oracle公司)于1995年发布。它的设计目标是“简单、健壮、安全、平台独立...
在描述中,"Java在企业中的应用"部分强调了Java作为一种强大的工具,对于企业级开发的重要性。Java具有跨平台的特性,可提供稳定、高效的解决方案,尤其在处理大量数据和复杂业务逻辑的数据库应用中,Java与JDBC的...
`java实验指导书.doc`和`说明.txt`文件可能提供了更详细的步骤和注意事项,例如处理异常、事务管理、批处理等高级话题。在实际开发中,还需要注意安全性,避免SQL注入攻击,可以使用预编译的`PreparedStatement`来...
《Java Web开发速学宝典》是一本专为初学者和有一定基础的开发者设计的教程,旨在快速掌握Java Web开发的核心技术。这本书涵盖了从基础到高级的诸多主题,包括Servlet、JSP、JDBC、MVC框架(如Spring MVC)、过滤器...
### Java编程与Oracle JDBC知识点概览 #### 一、引言 本书《Java Programming with Oracle JDBC》由Donald Bales编写,出版社为O'Reilly,首次出版于2002年1月,共有496页,ISBN号为0-596-00088-x。本书旨在教授...
手册将指导读者如何配置和使用这些IDE进行项目开发。 《Java项目开发实例自学手册》以实例贯穿始终,理论与实践相结合,让学习者能够边学边练,快速提升Java项目开发能力。无论是对于想要踏入Java开发领域的初学者...
Java Web开发是编程领域中的一个重要方向,它涵盖了使用Java技术栈构建Web应用程序的全过程。"零点起飞学Java Web开发"是一本...无论你是初学者还是希望巩固基础,这套资料都将为你的Java Web开发之旅提供宝贵的指导。
**JDBC官方文档详解** ...JDBC是Java开发中的基础工具,理解并熟练掌握JDBC的使用,对于开发高效、稳定的数据库应用至关重要。通过阅读和理解官方文档,开发者能够更好地利用JDBC特性,提升数据库操作的效率和安全性。
最后,我们将讨论如何使用 JDBC 和 JDBCProxy 来实现对 MySQL 数据库的访问和操作,并提供统一的 Java-MySQL 开发和测试方案。 JDBC 和 JDBCProxy 是实现对关系型数据库的访问和操作的重要工具。通过使用 JDBC,...
14. **数据库连接与JDBC**:Java通过JDBC API与各种数据库进行交互,掌握SQL语句编写、连接池管理和事务处理是数据库开发的基础。 15. **Maven或Gradle**:构建工具如Maven和Gradle简化了项目的构建和依赖管理,是...
"Java Web开发入行真功夫"这本书籍,由陈冈和陈智洁等专家编著,并由飞思科技产品研发中心监制,旨在为初学者提供全面的入门指导。虽然提供的源代码不包含光盘内容,但这些源代码和示例是学习过程中不可或缺的一部分...
《唯品会Java开发手册》是一份针对Java程序员的重要参考资料,尤其对于在唯品会这样的电商平台上进行开发的工程师来说,具有极高的实践指导价值。这份手册深入浅出地介绍了唯品会在Java开发过程中的最佳实践、规范...
这份文档集由一位经验丰富的开发者精心整理,包含了从基础到高级的各类主题,旨在为学习和提升Java技能提供全面的指导。以下是这个压缩包中可能包含的一些关键知识点: 1. **JDK**(Java Development Kit):是开发...
标题中的“java写的回合制游戏 oracle jdbc swing”表明这是一个基于Java编程语言开发的回合制游戏,其中使用了Oracle数据库作为后端存储,并且利用JDBC(Java Database Connectivity)技术进行数据交互。...
本教程旨在深入介绍通过JDBC在Java应用程序中执行的多种高级数据库操作,包括存储过程和高级数据类型等。示例代码针对DB2 Universal Database 7.2编写,但通过使用`DataSource`对象,轻松调整代码以适应其他数据库...
《Java Web开发实践教程——从设计到实现(第2版)》是一本深入探讨Java Web技术的权威指南,尤其适合初学者和有一定基础的...无论你是初入Java Web的新手还是寻求进阶的开发者,这个教程都能为你提供宝贵的指导。
Java开发资源库是一个全面的学习平台,专为Java初学者和有经验的开发者提供从入门到精通的全方位指导。这个资源库包含了大量的实例和项目,帮助用户深入理解和实践Java编程语言的核心概念和技术。以下是对资源库中...
《Java案例开发_项目开发风暴》是一份深入探讨Java编程技术及实际项目开发经验的PDF文档,旨在帮助读者提升在Java领域的实践技能。本资料详细介绍了多种Java编程技术和实际应用场景,通过实例分析和项目实战,让学习...