How to Insert Data into SQLite database using Java Programming

How to Insert Data into SQLite Database using Java Programming




In the previous tutorial, we learned how to connect any Java Application to the SQLite Database. We also learned the best way to manage SQLite databases on the computer for Java Application.

SQLite is very much popular and it’s one of the most used database engines on the globe. For example, the android phonebook is built on SQLite database and not only that but also other mobile applications across all mobile platforms.

This article will teach you how to insert data into an SQLite database using the Java Programming language. Learning how to insert data into the SQLite database using Java is very vital especially when developing the management systems.

This tutorial is second in the series of Java Database Tutorial, you can find the links to the other articles in this series at the bottom of this article.

SQLite Database Engine uses the same syntax as SQL to insert data to SQLite database,  i.e. “INSERT INTO table(column1, column2, …) VALUES(?, ?, ….) “.

How to Insert Data into SQLite Database using Java Programming

You must connect to your database before inserting any data. I have written a step by step article on how to Connecto to SQLite database using JDBC driver in Java.

The following code inserts data into an SQLite database:

private static void insert(String firstName, String secondName, String email, String password) {
  Connection con = DbConnection.connect();
  PreparedStatement ps = null; 
  try {
    String sql = "INSERT INTO users(firstName, secondName, email, password) VALUES(?,?,?,?) ";
    ps = con.prepareStatement(sql);
    ps.setString(1, firstName);
    ps.setString(2, secondName);
    ps.setString(3, email);
    ps.setString(4, password);
    ps.execute();
    System.out.println("Data has been inserted!");
  } catch(SQLException e) {
    System.out.println(e.toString());
    // always remember to close database connections
  } finally {
    try{
      ps.close();
      con.close();
    } catch(SQLException e) {
      System.out.println(e.toString());
    }
    
  }
}

You can call the insert method in your main function as shown below.

import java.sql.SQLException;

public class TheMain {
  public static void main(String [] args) {
    
    insert("Benson", "Karue", "benson@test.com", "myPassword");
    
    
  }
}

That’s how to insert data into the SQLite database using Java Programing

You May Also Like: 

  1. Java Database Connection
  2. How to Insert Data into SQLite database Using Java
  3. The best way to fetch data from SQLite database using Java
  4. How to Update Data Into SQLite Database using Java Programming
  5. How to delete a row (a record) from SQLite database using Java Programming
  6. How to get the number of rows in an SQLite Database Table Using Java