How do I check whether a SQLite database file exists using Java?
Asked Answered
A

7

8

I get the name of database file from a user, and I want to check if that file already exists. If it does exist, I want to show an error message to user, but I don't know how to check if the file exists.

public static void databaseConnect(String dbName) throws Exception
{
  if (/*same name exists*/) // How do I check this?
  {
    System.out.print("This database name already exists");
  }
  else
  {
    Class.forName("SQLite.JDBCDriver").newInstance();           
    conn = DriverManager.getConnection("jdbc:sqlite:/"+ dbName);
    stat = conn.createStatement(); 
  } 
}
Autograph answered 17/8, 2011 at 23:5 Comment(3)
Are you really checking if it exists or if a connection has already been opened?Est
No just to check if this database file(with name dbName) already exists or not!Autograph
Note that the slash after "sqlite:" and before the file path is not necessary with several of the SQLite JDBC drivers I've used.Spermiogenesis
B
14
public static void databaseConnect(String dbName) throws Exception {

   File file = new File (dbName);

  if(file.exists()) //here's how to check
     {
         System.out.print("This database name already exists");
     }
     else{

           Class.forName("SQLite.JDBCDriver").newInstance();            
           conn = DriverManager.getConnection("jdbc:sqlite:/"+ dbName);
           stat = conn.createStatement(); 

     }
Bunyan answered 17/8, 2011 at 23:9 Comment(5)
No it does not work. When I want to create new database file it says that name exists!Autograph
That's because the database already exists. In all the answers the connection will only be created one time, ever even between multiple runs.Est
so what should I do?I guess I did not get you sorry.Autograph
@Autograph I will take a big leap and try to guess your ultimate goal. Are you trying to run SQL statements the first time you create a database, then never again? Such as an initialization script for your database?Est
yes Andrew exactly after that I will create tables. I want to tell users that he wanted to have another database file name same as previous ones.(each time my program runs I create a database in my folder)Autograph
S
3

Assuming that your dbName parameter indicates the path to the SQLite file ("-wal" and "-shm" companion files notwithstanding), you can use the Java java.io.File class and its exists() predicate:

final File f = new File(dbName);
if (f.exists())
{
  if (f.isDirectory())
  {
    // Warn about the designated name being a directory.
  }
  else
  {
    // Warn about the designated name already existing as a file.
  }
}

Other checks could be warranted too, such as whether the process has the privilege to create the file, though ultimately SQLite will do a better job ensuring that all its requirements can be fulfilled.

Spermiogenesis answered 17/8, 2011 at 23:17 Comment(4)
my dbName is the name of database file and no path included.Autograph
In that case, the directory portion of the path is implicitly "./", indicating the current working directory of the host process.Spermiogenesis
you mean this? File file = new File ("jdbc:sqlite:/"+sessionName);Autograph
@Suny: You have to strip the jdbc:sqlite: part for sure; possibly also the first slash (a little experiment will tell you for sure).Bourn
F
1

I've found that the best way to do this is to instead check the size of the file. If you execute:

return new File(DB_NAME).exists() should equal True.

You should get a true back because it will create it. Instead check to make sure the file size is greater than 0. At least in this case you know there's data in the file without attaching and querying for results.

Instead do:

return new File(DB_NAME).length() > 0

Fart answered 8/3, 2017 at 12:50 Comment(0)
H
1

You can do something like this, I'm guessing you think you are creating a new file in your directory when you do "new File(name)", for what I've red, but that is not what is happening.

    public static void databaseConnect(String dbName) throws Exception {

      // new File(filename) does not create a new 
      // file in your file system
      File file = new File (dbName);

      if (file.exists()) 
      { // the file already existed and the program will enter this block
        System.out.print("Do something");
      }
      else 
      { //the file did not exist and you can send your error msg
        System.out.print("Do something else"); 
      } 
    }

I misinterpreted your question a few times, my bad, but I think that's it.

Haydenhaydn answered 9/8, 2019 at 8:59 Comment(0)
P
0

Something like this?

public boolean databaseExist()
{
    File dbFile = new File(DB_PATH + DB_NAME);
    return dbFile.exists();
}
Phloem answered 17/8, 2011 at 23:17 Comment(1)
with this File file = new File ("jdbc:sqlite:/"+sessionName); it does not work!never goes to if condition!Autograph
C
0

late, may it help :

public boolean didPackageCreate() {

    File dbfile = this.getDatabasePath("app.db");
    if(dbfile.exists()){
        // db exist
    }else{
       // db doesn't exist
    }
}
Cb answered 26/3, 2014 at 6:21 Comment(0)
M
0

To this day I believe this is the simplest way to achieve this. The couchbase lite database is created locally, so if it already exists, you add it to the config and create a Database instance to start working with it.

Here is the documentation: https://docs.couchbase.com/couchbase-lite/current/java/database.html#lbl-find-db-loc

import com.couchbase.lite.*;


 private static Database openOrCreateDatabase(String dbName) throws CouchbaseLiteException {
        DatabaseConfiguration config = new DatabaseConfiguration();
        File file=new File(config.getDirectory());
        if (!Database.exists(dbName,file)){
            System.out.println("Database created: "+dbName);
            return new Database(dbName, config);
        }else{
            config.setDirectory("../../"+dbName+".cblite2"); //path to your cblite folder
            return new Database(dbName, config);
        }
    }
Misapprehend answered 24/10, 2023 at 9:50 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.