Showing posts with label SQLite from Netbeans. Show all posts
Showing posts with label SQLite from Netbeans. Show all posts

Saturday, July 12, 2014

Making DBConnection to SQLite from Netbeans8.0

Key Learning: Netbeans does not allow direct conneciton to sqlite database. You require to import the jdbc connectivity jar available from the site: https://bitbucket.org/xerial/sqlite-jdbc . Once downloaded, goto the project from where the connection is being sought and right-click and goto properties >>Libraries>>Add Jar/Folder. Once added if the code is complied and run then it executes successfully. I have used here sqlite-jdbc-3.7.15-M1 downloaded from the above site.

I already have a sqlite database running in my D:\drive named as test.sqlite.
The sqlite database tables can be accessed from Firefox plugin for sqlite.

Some quick references from where the codes can be picked up are:
http://en.wikibooks.org/wiki/Java_JDBC_using_SQLite
https://bitbucket.org/xerial/sqlite-jdbc

I have successfully created my own code using the above references and is being reproduced here below for reference-

package dbconnection;
import java.sql.*;
import java.lang.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DbConnection {

    public static void main(String[] args) throws ClassNotFoundException {
        String sDrivername="org.sqlite.JDBC";
        Class.forName(sDrivername);
        String sTempDb="test.sqlite";
        String sJDBC="jdbc:sqlite:D:\\SQLite\\AllDBs\\test.sqlite";
        String sDBurl=sJDBC;
       
        int iTimeout=30;
       String sMaketable="CREATE TABLE testtable (Empno integer, Ename char);";
        String sMakeInsert="INSERT INTO testtable values(1234,'ST')";
        String sSelect="Select Empno from testtable";
        try {
            Connection conn=DriverManager.getConnection(sDBurl);
            Statement stmt=conn.createStatement();
             stmt.executeUpdate(sMaketable);
             stmt.executeUpdate(sMakeInsert);
             ResultSet rs=stmt.executeQuery(sSelect);
            while(rs.next()){
                String sResult=rs.getString("Empno");
                System.out.println(sResult);
               
            }
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException ex) {
            Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
       
       
    }
   
}