Connect Java with Sqlite3

Here we have explained an example in which we have to introduced concept of Java with Sqlite3 we discussed here concept behind establishing a connection with Java and sqlite3 database then perform operation of Create,Insert,Select Operation Reason behind switching to sqlite3 because sqlite3 is portable due to its smaller size and which suitable for any desktop application inside which we have to need smaller database, and good thing is that we don’t need to need to install any setup but also we have to store a .dll file and a shell file from specified location and take both files inside a single folder.

Download latest version SQLITE JDBC Driver from:   click here

Squlite-JDBC-Connection


//Import JDBC Packages
import java.sql.*;
import java.util.*;
public class SQLiteJDBC {
 public static void main(String args[]) {
  Connection con = null;
  Statement stmt = null;
  ResultSet rs = null;
  try {
   //Register JDBC Driver
   Class.forName("org.sqlite.JDBC");
   con = DriverManager.getConnection("jdbc:sqlite:D:/SQLiteOperation/main.db");
   // Location of SQLITE folder & main.db is default databse in SQLITE3 in your case you ca change it
   int choice;
   Scanner sb = new Scanner(System.in);
   System.out.println("Press 1 for Create table :");
   System.out.println("Press 2 for Insert Info :");
   System.out.println("Press 3 for Select Info :");
   choice = sb.nextInt();
   switch (choice) {
    case 1:

     // Creating Statement Object

     stmt = con.createStatement();
     String sqlString = "Create table test_table(name text,roll_no text)";
     stmt.executeUpdate(sqlString);
     stmt.close();
     con.close();
     break;
    case 2:

     // Creating Statement Object

     stmt = con.createStatement();
     stmt.executeUpdate("Insert into test_table(name,roll_no) values('Mohit','26')");
     stmt.close();
     con.close();
     break;
    case 3:

     // Creating Statement Object

     stmt = c.createStatement();
     rs = stmt.executeQuery("Select * from test_table");
     while (rs.next()) {
      String name = rs.getString("name");
      String roll_no = rs.getString("roll_no");
      System.out.println("name :" + name + "\nroll_no" + roll_no);
     }
     //statement close
     stmt.close();
     //connection close
     con.close();
     break;
   }
  } catch (Exception e) {
   System.err.println(e.getClass().getName() + ": " + e.getMessage());
   System.exit(0);
  }
  System.out.println("Opened database successfully");
 }
}