Help Center/
GaussDB/
Best Practices/
Best Practices for JDBC/
Best Practices for JDBC (Centralized Instances)/
Batch Query/
Procedure/
Complete Example
Updated on 2025-09-04 GMT+08:00
Complete Example
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; public class BatchQuery { public static Connection getConnection() throws ClassNotFoundException, SQLException { String driver = "com.huawei.gaussdb.jdbc.Driver"; // Specify the source URL of the database. (Adjust $ip, $port, and database based on the actual services.) String sourceURL = "jdbc:gaussdb://$ip:$port/database"; // Obtain the username and password from the environment variables. String userName = System.getenv("EXAMPLE_USERNAME_ENV"); String password = System.getenv("EXAMPLE_PASSWORD_ENV"); Class.forName(driver); return DriverManager.getConnection(sourceURL, userName, password); } public static void main(String[] args) { String selectSql = "select * from tab_test"; try (Connection conn = getConnection(); PreparedStatement preparedStatement = conn.prepareStatement(selectSql)) { conn.setAutoCommit(false); preparedStatement.setFetchSize(3); try (ResultSet resultSet = preparedStatement.executeQuery()) { while (resultSet.next()) { // Print only a portion of the query results. int id = resultSet.getInt(1); System.out.println("row:" + resultSet.getRow() + ",id :" + id); } ResultSetMetaData metaData = resultSet.getMetaData(); System.out.println("Result column: " + metaData.getColumnCount()); System.out.println("Type ID: " + metaData.getColumnType(1)); System.out.println("Type name: " + metaData.getColumnTypeName(1)); System.out.println("Column name: " + metaData.getColumnName(1)); } conn.commit(); } catch (ClassNotFoundException | Exception e) { throw new RuntimeException(e); } } }
Result Verification
Below are the execution results for Complete Example:
row:1,id :1 row:2,id :2 row:3,id :3 row:4,id :4 row:5,id :5 Result column: 2 Type ID: 4 Type name: int4 Column name: id
Rollback Method
To disable batch query, remove the fetchsize parameter from the connection string and reset setFetchSize to the default value of 0.
Parent topic: Procedure
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
The system is busy. Please try again later.
For any further questions, feel free to contact us through the chatbot.
Chatbot