Java調用postgresql 調用數據庫procedure
时间: 2023-09-27 14:05:50 浏览: 117
Java調用PostgreSQL數據庫中的存儲過程(procedure)需要以下步驟:
1. 在PostgreSQL數據庫中創建一個存儲過程(procedure)。
2. 在Java程序中使用JDBC API連接到PostgreSQL數據庫。
3. 使用JDBC API中的CallableStatement對象來調用存儲過程。
以下是一個示例代碼,演示如何使用Java調用PostgreSQL數據庫中的存儲過程:
```java
import java.sql.*;
public class CallStoredProcedure {
public static void main(String[] args) {
try {
// Connect to PostgreSQL database
Class.forName("org.postgresql.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/mydb", "username", "password");
// Prepare the stored procedure call
String call = "{ call my_stored_procedure(?, ?, ?) }";
CallableStatement cstmt = conn.prepareCall(call);
// Set the input parameters
cstmt.setInt(1, 1234);
cstmt.setString(2, "my_name");
cstmt.setDouble(3, 123.45);
// Register the output parameter
cstmt.registerOutParameter(3, java.sql.Types.VARCHAR);
// Execute the stored procedure
cstmt.execute();
// Get the output parameter value
String result = cstmt.getString(3);
System.out.println("Result: " + result);
// Close the statement and connection
cstmt.close();
conn.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
```
在上面的代碼中,我們首先使用Class.forName方法加載JDBC驅動程序,然後使用DriverManager.getConnection方法來連接到PostgreSQL數據庫。
接下來,我們準備要調用的存儲過程,並使用CallableStatement對象來設置輸入參數和註冊輸出參數。最後,我們執行存儲過程並獲取輸出參數的值。
注意,存儲過程的語法可能因PostgreSQL版本的不同而有所不同。請參考PostgreSQL文檔以獲取相關信息。
阅读全文
相关推荐


















