Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.sql.ResultSet;
- public class BetterHelloDatabase
- {
- public static void main (String[] args) throws Exception
- {
- final String dropTable = "DROP TABLE IF EXISTS dummy";
- final String createTable = "CREATE TABLE dummy (id numeric, response text)";
- final String insertSql = "INSERT INTO dummy VALUES(1,'Hello from the database')";
- final String selectSql = "SELECT response from dummy";
- final DbClass db = new DbClass("jdbc:sqlite:hello.db");
- try {
- db.execute(dropTable);
- db.execute(createTable);
- db.execute(insertSql);
- ResultSet rs = db.executeQuery(selectSql);
- try {
- while(rs.next())
- {
- String sResult = rs.getString("response");
- System.out.println(sResult);
- }
- } finally {
- try { rs.close(); } catch (Exception ignore) {}
- }
- } finally {
- try { db.closeConnection(); } catch (Exception ignore) {}
- }
- }
- }
- ===== DbClass.java =====
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- public class DbClass {
- public String url; // for advertising and debug purposes
- private String driver;
- private Connection conn;
- private Statement stmt;
- public DbClass(String url) throws Exception {
- this.url = url;
- setConnection();
- }
- private void setConnection() throws Exception {
- try {
- Class.forName("org.sqlite.JDBC");
- } catch (Exception e) {
- System.out.println("DriverName: " + driver + " was not available");
- System.err.println(e);
- throw e;
- }
- conn = DriverManager.getConnection(url);
- try {
- stmt = conn.createStatement();
- } catch (Exception e) {
- closeConnection();
- }
- }
- public void closeConnection() {
- if (stmt != null) { try { stmt.close(); stmt = null; } catch (Exception ignore) {} }
- if (conn != null) { try { conn.close(); conn = null; } catch (Exception ignore) {} }
- }
- public ResultSet executeQuery(String instruction) throws SQLException {
- return stmt.executeQuery(instruction);
- }
- public void execute(String instruction) throws SQLException {
- stmt.executeUpdate(instruction);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment