Skip to content

Instantly share code, notes, and snippets.

@juananpe
Last active December 4, 2019 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juananpe/4e81efe2dee6e27da114f4e31c4989d5 to your computer and use it in GitHub Desktop.
Save juananpe/4e81efe2dee6e27da114f4e31c4989d5 to your computer and use it in GitHub Desktop.
DBKudeatzaile (SQLite)
package ehu.isad.controller.db;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.io.File;
import java.sql.Connection;
import java.sql.Statement;
public class DBKudeatzaile {
Connection conn = null;
private void conOpen() {
try {
String url = "jdbc:sqlite::resource:ezarpenak.sqlite";
Class.forName("org.sqlite.JDBC").getConstructor().newInstance();
conn = (Connection) DriverManager.getConnection(url);
conn.setAutoCommit(false);
System.out.println("Database connection established");
} catch (Exception e) {
System.err.println("Cannot connect to database server " + e);
}
}
private void conClose() {
if (conn != null)
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Database connection terminated");
}
private ResultSet query(Statement s, String query) {
ResultSet rs = null;
try {
rs = s.executeQuery(query);
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
// singleton patroia
private static DBKudeatzaile instantzia = new DBKudeatzaile();
private DBKudeatzaile() {
this.conOpen();
}
public static DBKudeatzaile getInstantzia() {
return instantzia;
}
public ResultSet execSQL(String query) {
int count = 0;
Statement s = null;
ResultSet rs = null;
try {
s = (Statement) conn.createStatement();
if (query.toLowerCase().indexOf("select") == 0) {
// select agindu bat
rs = this.query(s, query);
} else {
// update, delete, create agindu bat
count = s.executeUpdate(query);
conn.commit();
System.out.println(count + " rows affected");
}
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment