Hallo,
beim Aufruf der insertInitialValues(); Methode, bekomme ich eine NullPointerException in preparedStatement.close();
Kann mir bitte dabei jemand helfen?
Anbei mein Code:
MAIN KLASSE:
getConnection KLASSE:
"Hauptklasse"
beim Aufruf der insertInitialValues(); Methode, bekomme ich eine NullPointerException in preparedStatement.close();
Kann mir bitte dabei jemand helfen?
Anbei mein Code:
MAIN KLASSE:
Java:
public class MainClass {
public static void main(String[] args) {
Connection connection = new dbConnection().getConnection();
if (connection != null) {
System.out.println("verbunden");
}
dbStatement dbStatement= new dbStatement();
// try {
// dbStatement.createTable();
// } catch (Exception e) {
// e.printStackTrace();
// }
try {
dbStatement.insertInitialValues();
} catch (Exception e) {
e.printStackTrace();
}
}
}
getConnection KLASSE:
Java:
public class dbConnection {
private static final String DB_Name= "usersTest.db";
private static final String PATH = "C:\\Users\\xxxxx\\Desktop\\Java\\src\\";
private static final String CONNECTION_STRING ="jdbc:sqlite:" + PATH + DB_Name;
public static Connection getConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection(CONNECTION_STRING);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
}
"Hauptklasse"
Java:
public class dbStatement {
private final String COLUMN_ID = "id";
private final String COLUMN_CATEGORY = "category";
private final String COLUMN_PRICE = "price";
private final String TABLE_NAME = "expenses";
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
public void createTable() throws SQLException {
String createTable = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME +
"(" +
COLUMN_ID + " INTEGER PRIMARY KEY, " +
COLUMN_CATEGORY + " TEXT, " +
COLUMN_PRICE + " REAL "
+")";
executeQuery(createTable);
}
public void executeQuery(String query) throws SQLException {
try {
connection = dbConnection.getConnection();
preparedStatement = connection.prepareStatement(query);
if (preparedStatement != null) {
preparedStatement.execute();
}
} finally {
preparedStatement.close();
connection.close();
}
}
public void insertInitialValues() throws SQLException {
String insertInitialValues= "INSERT INTO " + TABLE_NAME +
"(COLUMN_CATEGORY, COLUMN_PRICE)"
+ "VALUES (?, ?)";
try {
connection= dbConnection.getConnection();
preparedStatement= connection.prepareStatement(insertInitialValues);
preparedStatement.setString(1, "test");
preparedStatement.setDouble(2, 3.3);
if (preparedStatement != null) {
preparedStatement.executeUpdate();
}
} finally {
preparedStatement.close();
connection.close();
}
}
}