Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive

Running SQL Statements

Updated on 2025-02-27 GMT+08:00

In this section, you can execute basic SQL statements to create the customer_t1 table, execute a prepared statement to insert data in batches, execute a prepared statement to update data, and create and call stored procedures.

Running a Common SQL Statement

SQL statements are run on applications to operate a database. Operations such as SELECT, UPDATE, INSERT, and DELETE can be performed on XML data.

The prerequisite is that you have connected to the database using the connection object conn. Execute basic SQL statements to create the customer_t1 table as follows:

  1. Create a statement object by calling the createStatement method of the Connection API.

    1
    Statement stmt = conn.createStatement();
    

  2. Run the SQL statement by calling the executeUpdate method of the Statement API.

    1
    int rc = stmt.executeUpdate("CREATE TABLE customer_t1(c_customer_sk INTEGER, c_customer_name VARCHAR(32));");
    

  3. Close the statement object stmt by calling the close method of the Statement API.

    1
    stmt.close();
    

NOTE:
  • If an execution request (not in a transaction block) received in the database contains multiple statements, the request is packed into a transaction. VACUUM is not supported in a transaction block. If one of the statements fails, the entire request will be rolled back.
  • Use semicolons (;) to separate statements. Stored procedures, functions, and anonymous blocks do not support multi-statement execution. When preferQueryMode is set to simple, the statement does not execute the parsing logic, and the semicolons (;) cannot be used to separate statements in this scenario.
  • The slash (/) can be used as the terminator for creating a single stored procedure, function, anonymous block, or package body. When preferQueryMode is set to simple, the statement does not execute the parsing logic, and the slash (/) cannot be used as the terminator in this scenario.
  • JDBC caches SQL statements in PrepareStatement, which may cause memory bloat. If the JVM memory is small, you are advised to adjust preparedStatementCacheSizeMiB or preparedStatementCacheQueries.

Executing a Prepared Statement for Insertion

When a prepared statement processes multiple pieces of similar data, the database creates only one execution plan. This improves compilation and optimization efficiency.

The prerequisite is that the customer_t1 table has been created by executing the preceding basic SQL statements. Execute the prepared statement to insert data in batches as follows:

  1. Create the prepared statement object pst by calling the prepareStatement method of the Connection API.

    1
    PreparedStatement pst = conn.prepareStatement("INSERT INTO customer_t1 VALUES (?,?)");
    

  2. Call the corresponding API to set parameters for each piece of data and call addBatch to add SQL statements to the batch processing.

    1
    2
    3
    4
    5
    for (int i = 0; i < 3; i++) {
       pst.setInt(1, i);
       pst.setString(2, "data " + i);
       pst.addBatch();
    }
    

  3. Perform batch processing by calling the executeBatch method of the PreparedStatement API.

    1
    pst.executeBatch();
    

  4. Close the prepared statement object pst by calling the close method of the PreparedStatement API.

    1
    pst.close();
    

NOTE:

Do not terminate a batch processing action when it is ongoing; otherwise, database performance will deteriorate. Therefore, disable automatic commit during batch processing. Manually commit several lines at a time. The statement for disabling automatic commit is as follows:

conn.setAutoCommit(false);

Running a Prepared SQL Statement

Prepared statements are complied and optimized once but can be used in different scenarios by assigning different values. Using prepared statements improves execution efficiency. If you want to run a statement for several times, use a prepared statement.

The prerequisite is that the preceding prepared statement has been executed and data has been inserted into the customer_t1 table in batches. Execute the prepared SQL statement to update data as follows:

  1. Create the prepared statement object pstmt by calling the prepareStatement method of the Connection API.

    1
    PreparedStatement pstmt = conn.prepareStatement("UPDATE customer_t1 SET c_customer_name = ? WHERE c_customer_sk = 1");
    

  2. Set parameters by calling the setString method of the PreparedStatement API.

    1
    pstmt.setString(1, "new Data");
    

  3. Execute the prepared statement by calling the executeUpdate method of the PreparedStatement API.

    1
    int rowcount = pstmt.executeUpdate();
    

  4. Close the prepared statement object pstmt by calling the close method of the PreparedStatement API.

    1
    pstmt.close();
    

NOTICE:

After binding parameters are set in PrepareStatement, a B packet or U packet is constructed and sent to the server when the SQL statement is executed. However, the maximum length of a B packet or U packet cannot exceed 1023 MB. If the data bound at a time is too large, an exception may occur because the packet is too long. Therefore, when setting binding parameters in PrepareStatement, you need to evaluate and control the size of the bound data to avoid exceeding the upper limit of the packet.

Creating and Calling a Stored Procedure

GaussDB can call stored procedures through JDBC. The prerequisite is that the database connection is established using the connection object conn.

Create the testproc stored procedure as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// Create the stored procedure (containing the out parameter) in the database as follows:
create or replace procedure testproc 
(
    psv_in1 in integer,
    psv_in2 in integer,
    psv_inout inout integer
)
as
begin
    psv_inout := psv_in1 + psv_in2 + psv_inout;
end;
/

Call the testproc stored procedure as follows:

  1. Create a call statement object cstmt by calling the prepareCall method of Connection.

    1
    CallableStatement cstmt = conn.prepareCall("{? = CALL TESTPROC(?,?,?)}");
    

  2. Set parameters by calling the setInt method of CallableStatement.

    1
    2
    3
    cstmt.setInt(2, 50); 
    cstmt.setInt(1, 20);
    cstmt.setInt(3, 90);
    

  3. Register an output parameter by calling the registerOutParameter method in CallableStatement.

    1
    cstmt.registerOutParameter(4, Types.INTEGER);  // Register an OUT parameter of the integer type.
    

  4. Execute SQL statements by calling the execute method of CallableStatement.

    1
    cstmt.execute();
    

  5. Obtain the out parameter by calling the getInt method of CallableStatement.

    1
    int out = cstmt.getInt(4); 
    

  6. Close the call statement object cstmt by calling the close method of CallableStatement.

    1
    cstmt.close();
    

NOTICE:
  • If JDBC is used to call a stored procedure whose returned value is a cursor, the returned cursor cannot be used.
  • A stored procedure and a basic SQL statement must be run separately.
  • Output parameters must be registered for parameters of the inout type in the stored procedure.
NOTE:
  • Many database classes such as Connection, Statement, and ResultSet have a close() method. Close these classes after using their objects. Closing Connection objects is to close all the related Statement objects, and closing a Statement object is to close its ResultSet object.
  • Some JDBC drivers support named parameters, which can be used to set parameters by name rather than sequence. If a parameter has the default value, you do not need to specify any parameter value but can use the default value directly. Even though the parameter sequence changes during a stored procedure, the application does not need to be modified. Currently, the GaussDB JDBC driver does not support this method.
  • GaussDB does not support functions containing OUT parameters, or stored procedures and function parameters containing default values.
  • When you bind parameters in myConn.prepareCall("{? = CALL TESTPROC(?,?,?)}") during a stored procedure calling, you can bind parameters and register the first parameter as the output parameter according to the placeholder sequence or the fourth parameter as the output parameter according to the parameter sequence in the stored procedure. The preceding example registers the fourth parameter.

Creating and Calling a Stored Procedure (Input Parameters of the Composite Data Type)

The following shows how to create and call a stored procedure whose input parameters are of the composite data type in A-compatible mode. The prerequisite is that the database connection is established using the connection object conn.

Create the test_proc stored procedure as follows:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// Create a composite data type in the database.
CREATE TYPE compfoo AS (f1 int, f3 text);
// Create the following stored procedure (containing the out parameter) in the database:
create or replace procedure test_proc
(
    psv_in in compfoo,
    psv_out out compfoo
)
as
begin
    psv_out := psv_in;
end;
/

Call the test_proc stored procedure as follows:

  1. After setting behavior_compat_options to 'proc_outparam_override', create the call statement object cs by calling the prepareCall method of Connection.

    1
    2
    3
    Statement statement = conn.createStatement();
    statement.execute("set behavior_compat_options='proc_outparam_override'");
    CallableStatement cs = conn.prepareCall("{ CALL TEST_PROC(?,?) }");
    

  2. Set parameters by calling the set method of CallableStatement.

    1
    2
    3
    4
    PGobject pGobject = new PGobject();
    pGobject.setType("public.compfoo"); // Set the composite type name. The format is "schema.typename".
    pGobject.setValue("(1,demo)"); //: Bind the value of the composite type. The format is "(value1,value2)".
    cs.setObject(1, pGobject);
    

  3. Register an output parameter by calling the registerOutParameter method in CallableStatement.

    1
    2
    //Register an out parameter of the composite type. The format is "schema.typename".
    cs.registerOutParameter(2, Types.STRUCT, "public.compfoo");   
    

  4. Execute SQL statements by calling the execute method of CallableStatement.

    1
    cs.execute();
    

  5. Obtain the output parameter by calling the getObject method in CallableStatement.

    1
    2
    3
    4
    PGobject result = (PGobject)cs.getObject(2);  // Obtain the out parameter.
    result.getValue(); // Obtain the string value of the composite type.
    result.getArrayValue(); // Obtain the array values of the composite type and sort the values according to the sequence of columns of the composite type.
    result.getStruct(); // Obtain the subtype names of the composite type and sort them according to the creation sequence.
    

  6. Close the call statement object cs by calling the close method of CallableStatement.

    1
    cs.close();
    

NOTE:
  • After the A-compatible mode is enabled, you must use the {call proc_name(?,?)} format to call a stored procedure and use the {? = call func_name(?,?)} format to call a function. The question mark (?) on the left of the equal mark is the placeholder for the return value of the function and is used to register the return value of the function.
  • After setting behavior_compat_options to 'proc_outparam_override', re-establish the connection. Otherwise, the stored procedures and functions cannot be correctly called.
  • If a function or stored procedure contains a composite type, bind and register parameters in the schema.typename format.

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback