简体   繁体   中英

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.

To be more specific - what JDBC API should one use to execute PL/SQL or T-SQL blocks that return ResultSet s?

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:

  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.

And so, I was wondering if this JDBC API is the best way to execute such queries. In case it is, then there must be a bug in the specific JDBC driver implementation i'm using.

A CallableStatement is generally the way to go. This link gives an example how to do it in Oracle:

Using Cursor Variables

Note that you get a Cursor , not a ResultSet .

In T-SQL (which I don't know well) a CallableStatement with executeQuery should work as expected, see this link:

JDBC: CallableStatement

You need to provide the connection information beforehand to execute the SQL. You cannot infer the database from the SQL. So I don't think there is any such API which is present to handle such queries.

You can use the standard 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();
   } 
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM