Read data from sqlite database - Java JDBC

Java examples for JDBC:Sqlite

Description

Read data from sqlite database

Demo Code



import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import org.sqlite.JDBC;

public class Sqlite {
    public static void main(String[] args) {
      try{/*from  www.j av  a  2  s. c o m*/
        Sqlite sqlite = new Sqlite();
          String sql="select id,name,email from users";
          ResultSet rs = sqlite.select(sql);
          while(rs.next()){
          System.out.println("ID:"+rs.getString(1)+"\n"+rs.getString(2)+" "+rs.getString(3));
          }
      }catch (Exception e){
        e.printStackTrace();;
      }
    }
    
    private Connection conn = null;
    private String url = "jdbc:sqlite:";
    private String driver = "org.sqlite.JDBC";
    private String fileName = "/home/abc/workspace/ConnectDatabase/sqlite/Jack.db";

    public Connection create() {
      try {
        Class.forName(driver);
        conn = DriverManager.getConnection(url+fileName);
      } catch (Exception ex) {
        System.out.println("");
      }
      return conn;
    }

    public ResultSet select(String sql) {
      Connection conn = create();
      ResultSet rs = null;
      try {
        Statement st = conn.createStatement();
        rs = st.executeQuery(sql);
      } catch (Exception e) {
        System.out.println(e);
      } finally{
        //conn.close();
      }
      return rs;
    }

    public void execute(String sql) {
      Connection conn = create();
      ResultSet rs = null;
      try {
        Statement st = conn.createStatement();
        st.executeUpdate(sql);
      } catch (Exception e) {
        System.out.println(e);
      }

    }
}

Related Tutorials