2

I am trying to call a pre configured function using java code. This is the code i am using:

Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection("jdbc:postgresql://" + ip + ":5432/" + db,
                            username, password);
c.setAutoCommit(false);
stmt = c.createStatement();
stmt.executeQuery( "SELECT public.myFunc ("1","2","3"));

stmt.close();
c.close();

The function itself has some validation and in the end an INSERT command. When I run the query from pgAdmin, I can see that the row is added, but when I run the same query as written above, nothing happens.

Also tried replacing the executeQuery with execute and executeUpdate.

0

1 Answer 1

3

You can read the documentation about the right way of Calling Stored Functions, in your case you can use :

CallableStatement callStmt = c.prepareCall("{call myFunc(?, ?, ?)}");
callStmt.setString(1, "1");
callStmt.setString(2, "2");
callStmt.setString(3, "3");
callStmt.execute();
callStmt.close();

Important about your code

  • If you mean to use Integer 1 instead of String "1" you have to change callStmt.setString to callStmt.setInt
  • The default schema of postgres is public so you don't need to mention it, you can mention it if you use another schema
  • The quote in Java " should be escaped by \"
  • Don't concatenate attributes with your query, this can cause Syntax error and SQL Injection
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the quick answer, I have applied your solution but the result is the same, I run the query successfully but the change is not reflected in the DB.
Did you try it with setAutoCommit or without it, it seems you dont commit your statement
THANKS!! that was the issue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.