Java and Offline Databases

Asked

Viewed 3,561 times

13

I need some help with a Java database. I want to make a database that the program generates a file, such as "database.db" and this file I can access without any internet connection, using only the mentioned file.

How do I do it?

What you call this kind of database "offline"?

I can use Access?

  • Your application is desktop or web?

  • Do you want to "make a database" ? or do you want to use a database? in principle all databases write the data somewhere/file and you can access it localhost or remote.

3 answers

11


Download and install the Sqlite and the driver for the Sqlite

Sqlite is a server-less database system, in which the database will be a single file on the computer. There is more information about it on Wikipedia.

Create the bank

import java.sql.*;

public class SQLiteJDBC
{
  public static void main( String args[] )
  {
    Connection c = null;
    try {
      Class.forName("org.sqlite.JDBC");
      c = DriverManager.getConnection("jdbc:sqlite:test.db");
    } catch ( Exception e ) {
      System.err.println( e.getClass().getName() + ": " + e.getMessage() );
      System.exit(0);
    }
    System.out.println("Banco aberto com sucesso");
  }
}

Create a table

import java.sql.*;

public class SQLiteJDBC
{
  public static void main( String args[] )
  {
    Connection c = null;
    Statement stmt = null;
    try {
      Class.forName("org.sqlite.JDBC");
      c = DriverManager.getConnection("jdbc:sqlite:test.db");
      System.out.println("Banco de dados fora aberto com sucesso");

      stmt = c.createStatement();
      String sql = "CREATE TABLE TABELA " +
                   "(ID INT PRIMARY KEY     NOT NULL," +
                   " NOME           TEXT    NOT NULL, " + 
                   " IDADE            INT     NOT NULL)"; 
      stmt.executeUpdate(sql);
      stmt.close();
      c.close();
    } catch ( Exception e ) {
      System.err.println( e.getClass().getName() + ": " + e.getMessage() );
      System.exit(0);
    }
    System.out.println("A tabela TABELA foi criada com sucesso");
  }
}

Note: could use Access (not recommend because its focus is local use). But it would have to make the connection anyway the only difference is that the host of your db would be localhost. If you want to see how to use Access I suggest you see that link

4

  • 2

    +1 I’ve used HSQLDB in the past (in real projects) and it works great! In general I recommend the same Sqlite (because the support for it is wider, in case the database needs to be accessed by programs in other languages), but for a pure Java solution the HSQLDB is an excellent option.

2

Browser other questions tagged

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