Java and Offline Databases

13

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

How do I do this?

What is the name of this type of database "offline"?

Can I use Access?

    
asked by anonymous 19.08.2014 / 22:18

3 answers

11

Download and install SQLite and the SQLite

SQLite is a serverless database system in which the database will be a single file on the computer. More information about the same is available at 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: You could use Access (I do not recommend focusing on local usage). 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 that you see this link

    
19.08.2014 / 22:35
4

Another solution would be to use HSQLDB. link . You only need to configure it to save the data in a file and not in memory, as is the default configuration.

    
20.08.2014 / 12:05
2

Another option is to use H2 Database. I used it in an application does not have much time, and I liked it.

Click here for the official H2 Database

Click here for a tutorial with Eclipse, or Click here for a tutorial with NetBeans, or click here to the H2 Database Tutorials page.

    
22.08.2014 / 14:34