2

I have a desktop program which uses an embedded data base mechanism. For the first time a user will execute a program, it must create a database. So that, next time there is a database and there is no need to create it.

How do I check if there is database and create it if necessary?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Dmitry
  • 1,117
  • 1
  • 9
  • 11
  • 2
    Which embedded database will you be using? – Peter Tillemans May 31 '10 at 12:41
  • 4
    @Dmitry accept some of your answers that will improve your chances of getting your question answered – ant May 31 '10 at 12:42
  • how about you try to open it, and if you get an error, it's not there? – Bryan Oakley May 31 '10 at 12:54
  • that is a good variant for a programmer, not for a user =) And an embedded data base mechanism starts with a program/ My question was how to check if there is a necessary data base/ In my program it is called AdressBook – Dmitry May 31 '10 at 12:58
  • 1
    See http://stackoverflow.com/questions/2935266/how-to-deploy-a-java-swing-application-with-an-embedded-javadb-database – Jonas May 31 '10 at 13:05

2 Answers2

5

Use the create=true attribute in the JDBC URL, like this:

Connection conn = DriverManager.getConnection("jdbc:derby:sampleDB;create=true");

See the Apache Derby Reference Manual:

create=true attribute

Creates the standard database specified within the database connection URL Derby system and then connects to it. If the database cannot be created, the error appears in the error log and the connection attempt fails with an SQLException indicating that the database cannot be found.

If the database already exists, creates a connection to the existing database and an SQLWarning is issued.

You probably have to catch the SQLWarning (this is an exception) but you could safely ignore it.

Jesper
  • 202,709
  • 46
  • 318
  • 350
1

I'm make creating the database part of the installation script so you can always count on it being there.

Ok, but how to do it so that it would work on any platform?

If you're using Derby and Java, it'll work on every platform. You'll just have to write different installation scripts: .bat or .cmd for Windows, .sh for Linux and Mac. Not too strenuous.

May be there is a way to check if there is one and if there is no create it?

Try making a JDBC connection. If it fails, execute the DDL SQL.

duffymo
  • 305,152
  • 44
  • 369
  • 561
  • Ok, but how to do it so that it would work on any platform? May be there is a way to check if there is one and if there is no create it? – Dmitry May 31 '10 at 12:49
  • you can't always count on it being there. What if the user manually deletes the database after installation? Then you're right back to the original problem. – Bryan Oakley May 31 '10 at 12:55