Java JDBC开发指导

2 篇文章 0 订阅

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值