Skip to content

Instantly share code, notes, and snippets.

@DimasInchidi
Created April 5, 2017 19:22
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 DimasInchidi/095696133b6d843d06871a7b9e01bac3 to your computer and use it in GitHub Desktop.
Save DimasInchidi/095696133b6d843d06871a7b9e01bac3 to your computer and use it in GitHub Desktop.
Simple SQLite in java connection sample
import static java.lang.Class.forName;
import static java.sql.DriverManager.getConnection;
import java.sql.*;
import java.util.*;
public class db {
private static final String JDBC_DRIVER;
private static final String DATABASE_URL;
static {
JDBC_DRIVER = "org.sqlite.JDBC";
DATABASE_URL = "jdbc:sqlite:databasename.db";
}
private Connection con;
private Statement stmt;
public void db() {
//CREATE TABLE Users (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, username VARCHAR(55) UNIQUE, password VARCHAR(55), division VARCHAR(55))
if (Update("CREATE TABLE Users "
+ "(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, username VARCHAR(55) UNIQUE, "
+ "password VARCHAR(55), division VARCHAR(55));")) {
Update("INSERT INTO Users (id, username, password, division) \n"
+ " VALUES (NULL, 'anUser', 'apassword', 'division');");
}
}
/**
* @return Created Connection DB
*/
public Connection java_db() {
Connection connect;
try {
forName(JDBC_DRIVER);
connect = getConnection(DATABASE_URL);
} catch (SQLException | ClassNotFoundException se) {
connect = null;
System.out.println(se.getMessage());
}
return connect;
}
public boolean Update(String Query) {
try {
con = java_db();
Query = Query.replaceAll("`", "\"");
System.out.println(Query);
stmt = con.createStatement();
stmt.executeUpdate(Query);
return true;
} catch (SQLException ex) {
return false;
} finally {
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException ignored) {
}
try {
if (con != null) {
con.close();
}
} catch (SQLException se) {
se.printStackTrace();
}//end finally try
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment