Search code examples
javasqlitedatabase-connection

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


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(); 
  } 
}

Solution

  • 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(); 
    
         }