database 如何使用H2数据库创建存储过程?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3098905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 07:45:48  来源:igfitidea点击:

How to create stored procedure using H2 database?

databasestored-proceduresh2

提问by user351687

Has anyone tried to create stored procedures using the H2 database?

有没有人尝试过使用 H2 数据库创建存储过程?

回答by Thomas Mueller

To access the database within a Java function, you do need a connection. For H2, there are two ways to get such a connection:

要在 Java 函数中访问数据库,您确实需要一个连接。对于H2,有两种方法可以得到这样的连接:

Solution 1: If the first parameter of the Java function is a java.sql.Connection, then the database provides the connection. For SQL, this is a 'hidden' parameter, meaning you can't and don't need to set it explicitly. This is documented: User-Defined Functions and Stored Procedures, "Functions That Require a Connection". Example:

解决方案 1:如果 Java 函数的第一个参数是java.sql.Connection,则数据库提供连接。对于 SQL,这是一个“隐藏”参数,这意味着您不能也不需要显式设置它。这被记录在案:用户定义的函数和存储过程,“需要连接的函数”。例子:

CREATE ALIAS QUERY AS $$
ResultSet query(Connection conn, String sql) throws SQLException {
    return conn.createStatement().executeQuery(sql);
} $$;
CALL QUERY('SELECT * FROM DUAL');

Solution 2: For compatibility with Apache Derby and Oracle, You can open a new connection within the Java function using DriverManager.getConnection("jdbc:default:connection"). This feature is available in H2 version 1.3.151 and newer, and it it disabled by default. To enable it, append ;DEFAULT_CONNECTION=TRUEto the database URL. It's a problematic feature because the Oracle JDBC driver will try to resolve this database URL if it is loaded before the H2 driver. So basically you can't use the feature if the Oracle driver is loaded (I consider this a bug in the Oracle driver).

解决方案 2:为了与 Apache Derby 和 Oracle 兼容,您可以使用DriverManager.getConnection("jdbc:default:connection"). 此功能在 H2 版本 1.3.151 及更高版本中可用,默认情况下禁用。要启用它,请附加;DEFAULT_CONNECTION=TRUE到数据库 URL。这是一个有问题的特性,因为如果它在 H2 驱动程序之前加载,Oracle JDBC 驱动程序将尝试解析此数据库 URL。因此,如果加载了 Oracle 驱动程序,基本上您将无法使用该功能(我认为这是 Oracle 驱动程序中的一个错误)。