[英]Running PL/SQL and T-SQL Through JDBC
I'm wondering what's the best way to run a PL/SQL or T-SQL code blocks through JDBC. 我想知道通过JDBC运行PL / SQL或T-SQL代码块的最佳方法是什么。
To be more specific - what JDBC API should one use to execute PL/SQL or T-SQL blocks that return ResultSet
s? 更具体地说 - 应该使用什么JDBC API来执行返回
ResultSet
的PL / SQL或T-SQL块?
Update: 更新:
Even more specifically - I have a generic code that receives SQL code (may be SQL, PL/SQL or T-SQL) as an input, loads the appropriate JDBC driver according to the required database, and executes the given SQL code as follows: 更具体地说 - 我有一个通用代码,它接收SQL代码(可能是SQL,PL / SQL或T-SQL)作为输入,根据所需的数据库加载相应的JDBC驱动程序,并执行给定的SQL代码,如下所示:
Statement stmt = conn.createStatement ();
ResultSet rs = stmt.executeQuery("BEGIN some code END SELECT * FROM MY_TABLE");
while (rs.next ()) {
System.out.println (rset.getString (1));
}
This returns no ResultSet
when using some T-SQL or PL/SQL objects like cursors for example. 例如,在使用某些T-SQL或PL / SQL对象(如游标)时,不会返回
ResultSet
。
And so, I was wondering if this JDBC API is the best way to execute such queries. 所以,我想知道这个JDBC API是否是执行此类查询的最佳方式。 In case it is, then there must be a bug in the specific JDBC driver implementation i'm using.
如果是,那么我正在使用的特定JDBC驱动程序实现中必定存在错误。
A CallableStatement
is generally the way to go. CallableStatement
通常是要走的路。 This link gives an example how to do it in Oracle: 此链接提供了如何在Oracle中执行此操作的示例:
Note that you get a Cursor
, not a ResultSet
. 请注意,您获得了
Cursor
,而不是ResultSet
。
In T-SQL (which I don't know well) a CallableStatement
with executeQuery
should work as expected, see this link: 在T-SQL(我不太清楚)中,带有
executeQuery
的CallableStatement
应该按预期工作,请参阅此链接:
You need to provide the connection information beforehand to execute the SQL. 您需要事先提供连接信息以执行SQL。 You cannot infer the database from the SQL.
您无法从SQL推断数据库。 So I don't think there is any such API which is present to handle such queries.
因此,我认为没有任何此类API可用于处理此类查询。
You can use the standard JDBC API. 您可以使用标准JDBC API。 An example from here :
这里的一个例子:
import java.sql.*;
import oracle.jdbc.pool.OracleDataSource;
class JdbcTest {
public static void main (String args []) throws SQLException {
// Create DataSource and connect to the local database
OracleDataSource ods = new OracleDataSource();
ods.setURL("jdbc:oracle:thin:@//myhost:1521/orcl");
ods.setUser("scott");
ods.setPassword("tiger");
Connection conn = ods.getConnection();
// Query the employee names
Statement stmt = conn.createStatement ();
ResultSet rset = stmt.executeQuery ("SELECT ename FROM emp");
// Print the name out
while (rset.next ())
System.out.println (rset.getString (1));
//close the result set, statement, and the connection
rset.close();
stmt.close();
conn.close();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.