Search code examples
javasqljdbccallable-statement

How to call a 'view' using callablestatement


I thought it would be a simple google search, but I can't find an answer to this:

I'm moving Access db to SQL Server, I have turned some of the queries into views. My Java application used to call every query using simple:

{ call dbo.GetOtherRanges() } //Well, not entirely true - Access did not use 'dbo' schema in front of the name

This works for stored procedures. But when I do that on views I receive the following:

[SQL Server]The request for procedure 'GetOtherRanges' failed because 'GetOtherRanges' is a view object.

I thought it would be as simple as removing the () brackets after the name of the view, but that didn't do the trick.

  • How do I 'call' the views using JDBC CallableStatment?
  • Is there a different way of calling table-valued functions as well?

Solution

  • Views can be accessed just like Tables in JDBC.

    You dont need a CallableStatement for this.

    Just using Statement or PreparedStatement should be enough.

    In case you need help how-to, following is a sample code found here Use view name instead of Table1

    public void connectToAndQueryDatabase(String username, String password) {
    
        Connection con = DriverManager.getConnection(
                             "jdbc:myDriver:myDatabase",
                             username,
                             password);
    
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
    
        while (rs.next()) {
            int x = rs.getInt("a");
            String s = rs.getString("b");
            float f = rs.getFloat("c");
        }
    }