JDBC optimization skills

xiaoxiao2021-03-06  22

Here are some commonly used JDBC tips, perhaps improve your system's execution speed.

1.

When using PreparedStateMent / CallableStatement, try to use the setParams it provides.

Below is a wrong way:

Callablestatement cstmt = conn.preparecall

"{Call getCustName (12345)}");

ResultSet RS = cstmt.executeQuery ();

Below is the correct way:

Callablestatement cstmt - conn.preparecall

"{CALL getCustName (?)}");

CSTMT.SETLONG (1,12345);

ResultSet RS = cstmt.executeQuery ();

2. Use a bulk update method

It is generally updated using this method:

PreparedState ps = conn.preparestatement

"INSERT INTO EMPLOYEES VALUES (?,?,?)");

FOR (n = 0; n <100; n ) {

ps.setstring (name [n]);

Ps.setlong (ID [n]);

Ps.setint (Salary [n]);

ps.executeUpdate ();

}

If you use JDBC's advanced features, batch updates should have higher efficiency:

PreparedState ps = conn.preparestatement

"INSERT INTO EMPLOYEES VALUES (?,?,?)");

FOR (n = 0; n <100; n ) {

ps.setstring (name [n]);

Ps.setlong (ID [n]);

Ps.setint (Salary [n]);

ps.addbatch ();

}

ps.executebatch ();

3. Correct use of the resultSet GET method

Try not to use methods such as RS.GetObject (), and if you still need more efficient, use rs.getstring (1) to get a field value through field index marks, rather than use iv.getstring ("UserName") This method is to obtain a field value.

4. Take the value of the automatic increase of the type of record that has just been added

If your JDBC driver supports, there is a very convenient way to get the value of the self-add field, as follows:

INT rowcount = stmt.executeUpdate

"Insert Into LocalgeniusList (Name) Values ​​('Karen')",

Statement.return_Generated_Keys);

ResultSet RS = stmt.get generatedKeys ();

转载请注明原文地址:https://www.9cbs.com/read-43783.html

New Post(0)