sqlite+database url code example

Example: how to connect to sqlite database in java

public class DatabaseConnection {
    private static Connection con;

    /**
     * Singleton pattern
     * @return an instance of the connection
     */
    public static Connection getInstance() {
        if (con == null) {
            con = createConnection();
        }
        
        return con;
    }
    
    /**
     * creates a connection
     * @return the connection
     */
    public static Connection createConnection() {
        String dbUrl = "jdbc:sqlite:C:\\sqlite\\db\\Library.db";
        Connection c = null;
        try {
            Class.forName("org.sqlite.JDBC");
            c = DriverManager.getConnection(dbUrl);
            System.out.println("Opened database sucessfully");
        } catch (ClassNotFoundException | SQLException e) {
            System.out.println(e.getClass().getName() + " " + e.getMessage());
            System.exit(0);
        }

        return c;
    }
}

Tags:

Java Example