JDBC connection to SQLite in Java code in Netbeans

This topic describes how write Java code of connection to SQLite Database in Netbeans.

First step is create in Netbeans simple project.

Another step is register driver for SQLite.
You first need initialize Driver object from your sqlite jar file:
driverSQLite = new org.sqlite.JDBC();.
Next step is register this driver. For register is used DriverManager class with its static method: registerDriver. This method get one parameter as Driver object of database.
Call this method: DriverManager.registerDriver(driverSQLite ); . You have register driver.
After it You may connect to database. First for DriverManager class call static getConnection method. This method get one parameter as url path to your database: conSQLite= DriverManager.getConnection(urlSQLite);. My url is: urlSQLite = "jdbc:sqlite:C:/Users/Dora/Desktop/sqlite/test.db" ;

These all operations on databases must be in Exception block. Belove I present all application code for my test.db database.

package net.doraprojects;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.logging.Logger;

/* author Dora, doraprojects.net */
public class ConnetctToSQLite {

    public static void main(String[] args) 
     new Connect(); 

class Connect 
    private String urlSQLite;
    private Driver driverSQLite;
    private Connection conSQLite;  
    public Connect()
       urlSQLite = "jdbc:sqlite:C:/Users/Dora/Desktop/sqlite/test.db" ;  
       try {
             driverSQLite = new org.sqlite.JDBC();
	     DriverManager.registerDriver(driverSQLite );
             System.out.println("Driver for SQLite downloaded.");         
          } catch (Exception e)  { 
                                 System.out.println("Problem with download driver for SQLite: " + e.getMessage());
       try {   
             conSQLite= DriverManager.getConnection(urlSQLite);
             System.out.println("Connection to SQLite is done." );           
           } catch (Exception e) { 
                                 System.out.println("Problem with connection to SQLite: " + e.getMessage() );
            if(!conSQLite.isClosed()) { conSQLite.close(); System.out.println("Connection to SQLite closed." );  }
          } catch (Exception e) {  System.out.println("Problem with close connection of SQLite" );  }


End connection to database is realizing by close() method.

In project You must either add driver file for SQLite. So in Projects window right click the Libraries node and choose Add JAR/Folder from pop-up menu.

ss1The Add JAR/Folder window appears. Choose from your disk driver file and click Open button.

ss2In Libraries node in Projects window You see driver for SQLite.


If You run this application and all will be OK, the result appear:


Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.