• Post Reply Bookmark Topic Watch Topic
  • New Topic

Detect if a table exists  RSS feed

 
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am writing an application that uses JDBC to connect to a database. I want to create the necessary tables when the application starts, but only if the tables dont' exists already. Is there a generic way to use JDBC to detect if a certain table exists? I think there is a way using the database's metadata tables and select statements, but I'm not sure if this will be available across all platforms. I really want to create the tables programmatically so the user doesn't have to worry about it.

Layne
 
Ranch Hand
Posts: 15304
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you should probably do this in SQL and not in your java code per say. I don't know what all DB's support this syntax but I know in mysql you can do:

create table if not exists table_name....
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm developing with MySQL, but I think the target platform will use an Access database (at least initially). I'll see if this syntax works with Access as well.

I would guess that I need to do it with SQL, but I want to be able to execute the SQL statement in my Java program via JDBC. I'll have to see if this will work for multiple platforms.

Layne
 
Ranch Hand
Posts: 1141
1
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Layne,
Have you tried the "getTables()" method of the "java.sql.DatabaseMetaData" interface? Of-course, it is not guaranteed to be supported by every JDBC driver.

Good Luck,
Avi.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Originally posted by Avi Abrami:
Layne,
Have you tried the "getTables()" method of the "java.sql.DatabaseMetaData" interface? Of-course, it is not guaranteed to be supported by every JDBC driver.

Good Luck,
Avi.



Nope, I haven't come across that method yet. Thanks for the suggestion. Now that you mention it, I remember seeing a reference to the DatabseMetaData class, but I haven't looked at it further. It sounds like I should look at that class more closely. It might provide some solutions to other problems I hope to solve soon.

Layne
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!