Common Operation Examples
Example 1: Creating a Database Connection, Creating a Table, and Inserting Data
This example illustrates how to develop applications based on GaussDB JDBC APIs. Before executing the example, load the driver. For details about how to load the driver, see Loading a Driver.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 |
// DBTest.java // This example illustrates the main processes of JDBC-based development, covering database connection creation, table creation, and data insertion. // There will be security risks if the username and password used for authentication are directly written into code. It is recommended that the username and password be stored in the configuration file or environment variables (the password must be stored in ciphertext and decrypted when being used) to ensure security. // In this example, the username and password are stored in environment variables. Before running this example, set environment variables EXAMPLE_USERNAME_ENV and EXAMPLE_PASSWORD_ENV in the local environment (set the environment variable names based on the actual situation). import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.sql.CallableStatement; import java.sql.Types; public class DBTest { // Create a database connection. public static Connection GetConnection(String username, String passwd) { String driver = "com.mysql.jdbc.Driver"; String sourceURL = "jdbc:mysql://$ip:$port/database?useSSL=false&allowPublicKeyRetrieval=true"; Connection conn = null; try { // Load the database driver. Class.forName(driver).newInstance(); } catch (Exception e) { e.printStackTrace(); return null; } try { // Create a database connection. conn = DriverManager.getConnection(sourceURL, username, passwd); System.out.println("Connection succeed!"); } catch (Exception e) { e.printStackTrace(); return null; } return conn; }; // Execute a common SQL statement to create table customer_t1. public static void CreateTable(Connection conn) { Statement stmt = null; try { stmt = conn.createStatement(); // Execute common SQL statements. int rc = stmt .executeUpdate("CREATE TABLE customer_t1(c_customer_sk INTEGER, c_customer_name VARCHAR(32));"); stmt.close(); } catch (SQLException e) { if (stmt != null) { try { stmt.close(); } catch (SQLException e1) { e1.printStackTrace(); } } e.printStackTrace(); } } // Execute a prepared statement to insert data in batches. public static void BatchInsertData(Connection conn) { PreparedStatement pst = null; try { // Generate a prepared statement. pst = conn.prepareStatement("INSERT INTO customer_t1 VALUES (?,?)"); for (int i = 0; i < 3; i++) { // Add parameters. pst.setInt(1, i); pst.setString(2, "data " + i); pst.addBatch(); } // Perform batch processing. pst.executeBatch(); pst.close(); } catch (SQLException e) { if (pst != null) { try { pst.close(); } catch (SQLException e1) { e1.printStackTrace(); } } e.printStackTrace(); } } // Run a prepared statement to update data. public static void ExecPreparedSQL(Connection conn) { PreparedStatement pstmt = null; try { pstmt = conn .prepareStatement("UPDATE customer_t1 SET c_customer_name = ? WHERE c_customer_sk = 1"); pstmt.setString(1, "new Data"); int rowcount = pstmt.executeUpdate(); pstmt.close(); } catch (SQLException e) { if (pstmt != null) { try { pstmt.close(); } catch (SQLException e1) { e1.printStackTrace(); } } e.printStackTrace(); } } /** * Main process. Call static methods one by one. * @param args */ public static void main(String[] args) { // Create a database connection. String userName = System.getenv("EXAMPLE_USERNAME_ENV"); String password = System.getenv("EXAMPLE_PASSWORD_ENV"); Connection conn = GetConnection(userName, password); // Create a table. CreateTable(conn); // Insert data in batches. BatchInsertData(conn); // Run a prepared statement to update data. ExecPreparedSQL(conn); // Close the connection to the database. try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } |
The execution result of the preceding example is as follows:
Connection succeed!
Example 2: Batch Query
In this example, setFetchSize adjusts the memory usage of the client by using the database cursor to obtain server data in batches. It may increase network interaction and damage some performance.
The cursor is valid within a transaction. Therefore, disable automatic commit and then manually commit the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
// There will be security risks if the username and password used for authentication are directly written into code. It is recommended that the username and password be stored in the configuration file or environment variables (the password must be stored in ciphertext and decrypted when being used) to ensure security. // In this example, the username and password are stored in environment variables. Before running this example, set environment variables EXAMPLE_USERNAME_ENV and EXAMPLE_PASSWORD_ENV in the local environment (set the environment variable names based on the actual situation). import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.PreparedStatement; public class Batch { public static void main(String[] args) throws SQLException { String driver = "com.mysql.jdbc.Driver"; String username = System.getenv("EXAMPLE_USERNAME_ENV"); String passwd = System.getenv("EXAMPLE_PASSWORD_ENV"); String sourceURL = "jdbc:mysql://$ip:$port/database?useSSL=false&allowPublicKeyRetrieval=true"; Connection conn = null; try { // Load the database driver. Class.forName(driver).newInstance(); } catch (Exception e) { e.printStackTrace(); } try { // Create a database connection. conn = DriverManager.getConnection(sourceURL, username, passwd); System.out.println("Connection succeed!"); } catch (Exception e) { e.printStackTrace(); } // Disable automatic commit. conn.setAutoCommit(false); // Create a table. Statement st = conn.createStatement(); st.execute("create table mytable (cal1 int);"); // Insert 200 rows of data into the table. PreparedStatement pstm = conn.prepareStatement("insert into mytable values (?)"); for (int i = 0; i < 200; i++) { pstm.setInt(1, i + 1); pstm.addBatch(); } pstm.executeBatch(); conn.commit(); pstm.close(); // Open the cursor and obtain 50 rows of data each time. st.setFetchSize(50); int fetchCount = 0; ResultSet rs = st.executeQuery("SELECT * FROM mytable"); while (rs.next()) { fetchCount++; } System.out.println(fetchCount == 200); conn.commit(); rs.close(); // Disable the server cursor. st.setFetchSize(0); fetchCount = 0; rs = st.executeQuery("SELECT * FROM mytable"); while (rs.next()) { fetchCount++; } System.out.println(fetchCount == 200); conn.commit(); rs.close(); // Close the statement. st.close(); conn.close(); } } |
The execution result of the preceding example is as follows:
Connection succeed! true true
Enable automatic commit.
conn.setAutoCommit(true);
Example 3: Using Common Data Types
// There will be security risks if the username and password used for authentication are directly written into code. It is recommended that the username and password be stored in the configuration file or environment variables (the password must be stored in ciphertext and decrypted when being used) to ensure security.
// In this example, the username and password are stored in environment variables. Before running this example, set environment variables EXAMPLE_USERNAME_ENV and EXAMPLE_PASSWORD_ENV in the local environment (set the environment variable names based on the actual situation).
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.CallableStatement;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.Types;
public class Type {
public static void main(String[] args) throws SQLException {
String driver = "com.mysql.jdbc.Driver";
String username = System.getenv("EXAMPLE_USERNAME_ENV");
String passwd = System.getenv("EXAMPLE_PASSWORD_ENV");
String sourceURL = "jdbc:mysql://$ip:$port/database?useSSL=false&allowPublicKeyRetrieval=true";
Connection conn = null;
try {
// Load the database driver.
Class.forName(driver).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
try {
// Create a database connection.
conn = DriverManager.getConnection(sourceURL, username, passwd);
System.out.println("Connection succeed!");
} catch (Exception e) {
e.printStackTrace();
}
Statement st = conn.createStatement();
// Example of using the bit type
st.execute("create table if not exists t_bit(col_bit bit)");
PreparedStatement pstm1 = conn.prepareStatement("insert into t_bit values(?)");
pstm1.setBoolean(1,true);
pstm1.execute();
pstm1.close();
ResultSet rs1 = st.executeQuery(" select col_bit from t_bit;");
while (rs1.next()) {
System.out.println(rs1.getBoolean(1));
}
rs1.close();
// Example of using the float8 type
st.execute("create table if not exists t_float(col1 float8)");
PreparedStatement pstm2 = conn.prepareStatement("insert into t_float values(?)");
pstm2.setDouble(1, 123456.123);
pstm2.execute();
pstm2.close();
ResultSet rs2 = st.executeQuery(" select col1 from t_float;");
while (rs2.next()) {
System.out.println(rs2.getDouble(1));
}
rs2.close();
st.close();
// Close the connection to the database.
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
The execution result of the preceding example is as follows:
Connection succeed! false 123456.123
Example 4: Using the Streaming Read Function
Streaming read function: All data is read at a time by the server and sent to the socket buffer of a client until the buffer is full. If there is free space, the data continues to be sent to the buffer. At the same time, a JVM reads data from the buffer row by row.
The advantage is that the result is processed fast and no JVM memory overflow occurs. The disadvantage is that streaming read can only traverse backwards. Before data processing is complete or the statement is closed, no other operations can be performed in the current connection.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 |
// There will be security risks if the username and password used for authentication are directly written into code. It is recommended that the username and password be stored in the configuration file or environment variables (the password must be stored in ciphertext and decrypted when being used) to ensure security. // In this example, the username and password are stored in environment variables. Before running this example, set environment variables EXAMPLE_USERNAME_ENV and EXAMPLE_PASSWORD_ENV in the local environment (set the environment variable names based on the actual situation). import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Stream { // Create a database connection. public static Connection getConnection(String username, String passwd) { String driver = "com.mysql.jdbc.Driver"; String sourceURL = "jdbc:mysql://$ip:$port/database?useSSL=false&allowPublicKeyRetrieval=true"; Connection conn = null; try { // Load the driver. Class.forName(driver); } catch (Exception e) { e.printStackTrace(); return null; } try { // Create a connection. conn = DriverManager.getConnection(sourceURL, username, passwd); System.out.println("Connection succeed!"); } catch (Exception e) { e.printStackTrace(); return null; } return conn; } // Execute common SQL statements to create table t_user. public static void CreateTable(Connection conn) { Statement stmt = null; try { stmt = conn.createStatement(); // Execute common SQL statements. stmt.executeUpdate("DROP TABLE IF EXISTS t_user"); stmt.executeUpdate("CREATE TABLE t_user(id int, name VARCHAR(20));"); stmt.close(); } catch (SQLException e) { if (stmt != null) { try { stmt.close(); } catch (SQLException e1) { e1.printStackTrace(); } } e.printStackTrace(); } } // Execute a prepared statement to insert data in batches. public static void BatchInsertData(Connection conn) { PreparedStatement pst = null; try { // Generate a prepared statement. pst = conn.prepareStatement("INSERT INTO t_user VALUES (?,?)"); for (int i = 0; i < 20; i++) { // Add parameters. pst.setInt(1, i + 1); pst.setString(2, "name " + (i + 1)); pst.addBatch(); } // Perform batch processing. pst.executeBatch(); pst.close(); } catch (SQLException e) { if (pst != null) { try { pst.close(); } catch (SQLException e1) { e1.printStackTrace(); } } e.printStackTrace(); } } // Enable streaming read and query the content in the t_user table. public static void StreamingQuery(Connection conn) { PreparedStatement pst = null; ResultSet resultSet = null; try { // Query all values in the t_user table. pst = conn.prepareStatement("SELECT * FROM t_user"); pst.setFetchSize(Integer.MIN_VALUE); resultSet = pst.executeQuery(); while (resultSet.next()) { System.out.println(resultSet.getInt(1)); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { throw new RuntimeException(e); } } if (pst != null) { try { pst.close(); } catch (SQLException e) { throw new RuntimeException(e); } } } } public static void main(String[] args) throws Exception { String userName = System.getenv("EXAMPLE_USERNAME_ENV"); String password = System.getenv("EXAMPLE_PASSWORD_ENV"); Connection conn = getConnection(userName, password); CreateTable(conn); BatchInsertData(conn); StreamingQuery(conn); // Close the connection to the database. try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } |
The execution result of the preceding example is as follows:
Connection succeed! 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
When the streaming read function is used, you need to perform the resultSet.close() or statement.close() operation after the result set is used. Otherwise, the current connection is unavailable.
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.
For any further questions, feel free to contact us through the chatbot.
Chatbot