获取函数返回值
JDBC调用函数时获取返回值,以下示例展示返回值类型为bit和float8两种数据类型,其他数据类型可参考本示例。
代码运行的前提条件:根据实际情况添加opengaussjdbc.jar包(例如用户使用IDE执行代码,则需要在本地IDE添加opengaussjdbc.jar包)。
// 认证用的用户名和密码直接写到代码中有很大的安全风险,建议在配置文件或者环境变量中存放(密码应密文存放,使用时解密),确保安全。
// 本示例以用户名和密码保存在环境变量中为例,运行本示例前请先在本地环境中设置环境变量(环境变量名称请根据自身情况进行设置)EXAMPLE_USERNAME_ENV和EXAMPLE_PASSWORD_ENV。
// $ip、$port、database需要用户自行修改。
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.huawei.opengauss.jdbc.Driver";
String username = System.getenv("EXAMPLE_USERNAME_ENV");
String passwd = System.getenv("EXAMPLE_PASSWORD_ENV");
String sourceURL = "jdbc:opengauss://$ip:$port/database";
Connection conn = null;
try {
// 加载数据库驱动。
Class.forName(driver).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
try {
// 以非加密方式创建数据库连接。
conn = DriverManager.getConnection(sourceURL, username, passwd);
System.out.println("Connection succeed!");
} catch (Exception e) {
e.printStackTrace();
}
// 建表。
String createsql = "create table if not exists t_bit(col_bit bit)";
Statement stmt = conn.createStatement();
stmt.execute(createsql);
stmt.close();
// bit类型使用示例,注意此处bit类型取值范围[0,1]。
Statement st = conn.createStatement();
String sqlstr = "create or replace function fun_1()\n" + "returns bit AS $$\n"
+ "select col_bit from t_bit limit 1;\n" + "$$\n" + "LANGUAGE SQL;";
st.execute(sqlstr);
CallableStatement c = conn.prepareCall("{ ? = call fun_1() }");
// 注册输出类型,位串类型。
c.registerOutParameter(1, Types.BIT);
c.execute();
// 使用Boolean类型获取结果。
System.out.println(c.getBoolean(1));
// float8类型使用示例。
st.execute("create table if not exists t_float(col1 float8)");
PreparedStatement pstm = conn.prepareStatement("insert into t_float values(?)");
pstm.setDouble(1, 123456.123);
pstm.execute();
pstm.close();
// 函数返回值为float8的使用示例。
st.execute(
"create or replace function func_float() " + "return float8 " + "as declare " + "var1 float8; " + "begin "
+ " select col1 into var1 from t_float limit 1; " + " return var1; " + "end;");
CallableStatement cs = conn.prepareCall("{? = call func_float()}");
cs.registerOutParameter(1, Types.DOUBLE);
cs.execute();
System.out.println(cs.getDouble(1));
st.close();
// 关闭数据库连接。
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
上述示例的运行结果为:
Connection succeed! false 123456.123
当前JDBC不支持调用返回数据类型为money的存储过程和函数。