// You may find sections of this code useful
// Good example of DB connection using SQLite
// Written by S1, 2016 COMP9322 students: James Fang and Anton Jansson
// Attribute the authors properly if you are copying the code from
// this example

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import org.sqlite.SQLiteConfig;

public class SqliteConn {
	//
	private static final String DB_RESOURCE_NAME_PREFIX = "jdbc:sqlite:";
	private static final String DRIVER = "org.sqlite.JDBC";
	private static final String DB_LOCATION = System.getProperty("java.io.tmpdir") + File.separator + "FoundItApp" + File.separator; 
	private static final String DB_NAME = "FoundItApp.db";
	
	public static SqliteConn instance = new SqliteConn();
	
	private Connection connection = null; 
	
	private SqliteConn() {
		if (!databaseExists())
			createDatabase();
		else
			connect();
	}
	
	public static Connection GetConnection() {
		return instance.connection;
	}
	
	private void connect() {
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			System.out.println("Error: FATAL ERROR, cannot instantiate the driver " + DRIVER);
			return;
		} 
		try {  
	        SQLiteConfig config = new SQLiteConfig();  
	        config.enforceForeignKeys(true); 
	        System.out.println("Database file: " + DB_LOCATION + DB_NAME);
	        connection = DriverManager.getConnection(DB_RESOURCE_NAME_PREFIX + DB_LOCATION + DB_NAME, config.toProperties());
	        
	    } catch (SQLException ex) {
	    	ex.printStackTrace();
	    	System.out.println("Error: FATAL ERROR, failed to get connection " + DRIVER);
	    } 
	}
	
	private boolean databaseExists() {
		File file = new File(DB_LOCATION + DB_NAME);
		return file.exists();
	}
	
	private void createDatabase() {
		File file = new File(DB_LOCATION + DB_NAME);
		
		try {
			file.getParentFile().mkdirs();
			file.createNewFile();
		} catch (IOException e) {
			System.out.println("Error: FATAL ERROR, could not create DB file " + DB_LOCATION + DB_NAME);
			return;
		}
		
		connect();
		try {
			Statement stmt = connection.createStatement();
			stmt.execute(SqlDatabaseSetup.CREATE_USERS_TABLE);
			stmt.execute(SqlDatabaseSetup.CREATE_SAVED_JOBS_TABLE);
			System.out.println("Successfully crated database " + DB_LOCATION + DB_NAME);
		} catch (SQLException e) {
			e.printStackTrace();
			file.delete();
		}
	}
	
}

Resource created Wednesday 31 August 2016, 10:47:59 AM.

file: SqliteConn.java


Back to top

COMP9322 16s2 (Service Oriented Architectures) is powered by WebCMS3
CRICOS Provider No. 00098G