Resultset Return null in Java

Asked

Viewed 187 times

-1

I use the code below to check in Postgre if the table exists, running the Query in Pgadmin have as answer value null.

But apparently Resultset will never return null. Is there any way to compare RS with null, true or false ? It is also possible to create a new query, but I need to know what value RS ta returning.

Connection conn = Class_Conexao.GetConnection();
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT to_regclass('public.clientes_alter_log')"))

This is part that I connect and check if there is a Table. use an if/Else if available. Any idea how I can proceed ?

  • According to the manual the function to_regclass can return NULL("... These functions differ from a cast from text in that they don’t Accept a Numeric OID, and that they Return null rather than Throwing an error if the name is not found ... https://www.postgresql.org/docs/current/functions-info.html). An alternative is to consult the catalog: SELECT EXISTS 
(
 SELECT 1 
 FROM pg_tables
 WHERE schemaname = 'schema_name'
 AND tablename = 'table_name'
);.

  • I also used this select in other tables, actually in all, I read that toregclass guarantees me a faster response. But the problem is that if it does not exist in the bank should enter in the if(rs.next()) until then it is all right, but when it already exists it should fall into an Else or something of the kind, which contains stmt exexuteUpdate. but passes in 2. And if you have a FK falls into the exception

1 answer

3


First on its query you must assign a alias to the column:

ResultSet rs = stmt.executeQuery("SELECT to_regclass('public.clientes_alter_log') AS existencia"));

Then check whether the column value is null:

if (rs.next()) {
  final String existencia = rs.getString("existencia");
  return !rs.wasNull();
}

return false;

wasNull

Reports whether the last column read had a value of SQL NULL. Note that you must first call one of the getter methods on a column to Try to read its value and then call the method wasNull to see if the value read was SQL NULL.

In free translation:

Tells if the last column read had a value of SQL NULL. Note that you should first call one of the getter methods in a column to try to read its value and then call the method wasNull to see if the read value was SQL NULL.

  • very interesting, I will try to get value this way, because only taking the return of the resultset and using rs.next is not having the behavior I expect. Thank you!

  • friend! Thank you so much!!! at first I had exactly the result I was looking for!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.