All Downloads are FREE. Search and download functionalities are using the official Maven repository.

nl.tno.bim.nmd.services.SqliteDataService Maven / Gradle / Ivy

The newest version!
package nl.tno.bim.nmd.services;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;

public abstract class SqliteDataService {

	protected Connection connection;
	
	public abstract void login();
	
	public void logout() {
		try {
			if (this.connection == null || this.connection.isClosed()) {
				this.connection.close();
			}
		} catch (SQLException e) {
			System.err.println("Error occured in disconnecting from mapping service: " + e.getMessage());
		}
	}
	
	public Boolean getIsConnected() {
		try {
			return connection == null ? false : !connection.isClosed();
		} catch (SQLException e) {
			return false;
		}
	}

	protected String createSqlInsertStatement(String table, String[] headers, List values) {

		String valueString = String.join(",", 
				values.stream().map(ar -> "('" + String.join("','", ar) + "')").collect(Collectors.toList()));
		
		return "INSERT INTO " + table + " (" + String.join(",", headers) + ") VALUES " + valueString;
	}

	protected void deleteTable(String tableName) throws SQLException {
		this.executeAndCommitCommand("DROP TABLE IF EXISTS " + tableName);
	}

	protected void executeAndCommitCommand(String sqlCommand) throws SQLException {
		Statement statement = connection.createStatement();
		statement.setQueryTimeout(30);
		statement.executeUpdate(sqlCommand);
		statement.close();
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy