I have a simple Java program that connects to an empty sqlite database. I am trying to create a table, but get a null pointer exception when I try to execute the query.
- I made sure all the required jar's are there.
- I used the debugger to find the problematic line of code. It is line 51 of my code below. Another relevant line of code is line 113 of the Statement class, which I can post for reference, if necessary.
- I made sure that my statement was properly initialised
import java.sql.*;
public class SqliteConnection
{
public static Connection connect()
{
Connection conn = null;
try
{
// db parameters
String url = "jdbc:sqlite:/database.db";
// create a connection to the database
conn = DriverManager.getConnection(url);
System.out.println("Connection to SQLite has been established.");
}
catch (SQLException e)
{
System.out.println(e.getMessage());
}
finally
{
try
{
if (conn != null)
{
conn.close();
}
}
catch (SQLException ex)
{
System.out.println(ex.getMessage());
}
}
return conn;
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
Connection c = connect();
try
{
//create the table
Statement stmt = null;
stmt = c.createStatement();
String sql = "CREATE TABLE Car (CarID INT NOT NULL, Manufacturer TEXT, Type TEXT, FuelEfficiency REAL, PRIMARY KEY(CarID));";
stmt.execute(sql);
stmt.close();
c.close();
}
catch (Exception e)
{
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
Stack trace:
java.lang.NullPointerException
at org.sqlite.Stmt.execute(Stmt.java:113)
at SqliteConnection.main(SqliteConnection.java:52)