Java SQLite database, insert entry giving nullPointerException - java

I am trying to create a generic method that can add an entry into a SQLite database, using Eclipse and Java.
When the table name is hardcoded it works fine, but when I try to pass in the table name as a string it is giving me a nullPointerException.
below is the method that creates that table:
public static void Table()
{
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS COMPANY " +
"(ID INT PRIMARY KEY NOT NULL," +
" NAME TEXT NOT NULL, " +
" AGE INT NOT NULL, " +
" ADDRESS TEXT, " +
" SALARY REAL)";
stmt.executeUpdate(sql);
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Table created successfully");
}
and here is the method that inserts an entry into the created table. I want to pass in the table name through the method rather than hard coding it:
public static void Insert(String table, int id, String name, int age, String address, String salary)
{
Connection c = null;
PreparedStatement pstmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
String query="INSERT INTO "+table+" (ID,NAME,AGE,ADDRESS,SALARY) VALUES (?,?,?,?,?)";
PreparedStatement stmt = c.prepareStatement(query);
pstmt.setInt(1,id);
pstmt.setString(2,name);
pstmt.setInt(3, age);
pstmt.setString(4, address);
pstmt.setString(5, salary);
pstmt.executeUpdate();
pstmt.close();
c.commit();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Records created successfully");
}

You have small mistake
just you have created two different PreparedStatement object
So change
PreparedStatement stmt = c.prepareStatement(query);
to
pstmt = c.prepareStatement(query);

Related

jdbc: get date from sqlite database

I have saved the date in sqlite database as unixepoch value and while trying to fetch the date I'm getting the error: 'No such column exists 'Date'".
Here is how I create the table:
public void createActivityTable() {
Statement stmt = null;
try (Connection connection = connectionClass.connectToMainDb(true)) {
stmt = connection.createStatement();
String table = "CREATE TABLE IF NOT EXISTS EMPLOYEE_ACTIVITY (" +
"ActivityIndex INTEGER PRIMARY KEY AUTOINCREMENT," +
"employeeID INTEGER NOT NULL," +
"Date INTEGER NOT NULL," +
"PCName TEXT NOT NULL," +
"Amount REAL," +
"Activity TEXT NOT NULL," +
"FOREIGN KEY (employeeID) REFERENCES EMPLOYEES(employeeID) ON DELETE NO ACTION ON UPDATE CASCADE," +
"FOREIGN KEY (PCName) REFERENCES COMPUTERAVERAGE(PCName) ON DELETE NO ACTION ON UPDATE CASCADE" +
");";
stmt.executeUpdate(table);
stmt.close();
connection.close();
} catch (SQLException e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
Here is the insert method:
public void insertProductivity(int employeeID, double amount, String activityType, String pieceType) {
Statement stmt = null;
try (Connection connection = connectionClass.connectToMainDb(true)) {
stmt = connection.createStatement();
String query = "INSERT INTO EMPLOYEE_ACTIVITY (employeeID, Date, PCName, Amount, Activity, PieceType) " +
"VALUES ('" + employeeID + "', strftime('%s', 'now'), '" + User.getLoggedPC().replaceAll("[^a-zA-Z0-9]", "") +
"', '" + amount + "', '" + activityType + "', '" + pieceType + "');";
stmt.executeUpdate(query);
stmt.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
Here is the way I try to fetch the date where I get the exception in the rs.next while loop:
public void getStats() {
PreparedStatement stmt = null;
try (Connection connection = connectionClass.connectToMainDb(false)) {
String query = "SELECT datetime(Date, 'unixepoch') FROM EMPLOYEE_ACTIVITY;";
stmt = connection.prepareStatement(query);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getInt("Date"));
}
rs.close();
stmt.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
And i get the next error:
java.sql.SQLException: no such column: 'Date'
at org.sqlite.jdbc3.JDBC3ResultSet.findColumn(JDBC3ResultSet.java:48)
at org.sqlite.jdbc3.JDBC3ResultSet.getInt(JDBC3ResultSet.java:401)
at employee.stats.StatsHandler.getStatsByYear(StatsHandler.java:24)
at gui.Main.start(Main.java:20)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:748)
Your select statement specifies SELECT datetime(Date, 'unixepoch') so there is indeed no column called Date in the result set. You may want to give your column a name, for example:
SELECT datetime(Date, 'unixepoch') AS d
and then fetch column d.

sqlite java query does not insert into table

Have sqlite table named good_in with columns in_id, good_code, in_group, in_quantity, in_VATPaid
Here is my table example
and have method to insert records into it
public static void inputGoods(GoodsInput goodsinput){
String goodCode = goodsinput.getInGood().getGood_code();
int goodBatch = goodsinput.getInGroup();
int goodQuantity = goodsinput.getInQuantity();
double goodVATPaid = goodsinput.getInVatPaid();
String sqlInsert = "INSERT INTO good_in (good_code, in_group, in_quantity, in_VATPaid)"
+ " VALUES ('" + goodCode + "', " + "'" + goodBatch + "', " + "'" + goodQuantity
+ "', " + "'" +goodVATPaid + "');";
System.out.print(sqlInsert);
Connection conn = ConnectionFactory.ConnectDB();
try{
Statement statement = conn.createStatement();
statement.executeUpdate(sqlInsert);
}
catch(SQLException e){
}
}
Connection class
public static Connection ConnectDB(){
try{
Class.forName("org.sqlite.JDBC");
Connection con = DriverManager.getConnection("jdbc:sqlite:kahuyq.db");
return con;
} catch (HeadlessException | ClassNotFoundException | SQLException ex){ JOptionPane.showMessageDialog(null, ex); }
return null;
}
When I copy the printed query to sqlite manager it adds the row, but from java it ends program with no error but does not add row to my table.
What is wrong?
Have also other method that checks weather the good_code exists in table good which have only 2 columns id and good_code and if does not exist adds it. this method is accessed from GoodsInput constructor. When I delete the method from constructor the other method works fine.
Here is that method
public static void insertGoods(Good g){
String sqlSelect = "Select * from good where good_code = '"
+ g.getGood_code() + "'" ;
String sqlInsert = "INSERT INTO good (good_code)"
+ "VALUES ('" + g.getGood_code() +"')";
Connection conn = ConnectionFactory.ConnectDB();
try{
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(sqlSelect);
while(!rs.next()){
statement.executeUpdate(sqlInsert);
break;
}
}
catch(SQLException e){
}
}
Try to add
conn.commit();
after the execution of your statement.

Java UCanAccess- unwanted dollar signs

When I put my data onto MSAccess, it goes there with dollar signs before it. Here is my relevant code:
try (Connection conn = DriverManager.getConnection(
"jdbc:ucanaccess://" + dbPath
+ ";newdatabaseversion=V2010"
)) {
DatabaseMetaData dmd = conn.getMetaData();
try (ResultSet rs = dmd.getTables(null, null, tableName, new String[] { "TABLE" })) {
try (Statement s = conn.createStatement()) {
s.executeUpdate("CREATE TABLE " + tableName +" (Row COUNTER PRIMARY KEY, aColumn NUMBER , bColumn NUMBER)");
System.out.println("Table " + tableName + " created.");
}
}
conn.close();
}
}
catch (Exception f){
f.printStackTrace();
}
...
try{
statement.execute("DISABLE AUTOINCREMENT ON " + tableName );
statement.executeUpdate("INSERT INTO " + tableName
+ " ( Row, aColumn, bColumn)"
+ " VALUES ( "+(i+1)+", "+a+", "+b+")");
System.out.println("row " + i);
}
catch (Exception f ){
f.printStackTrace();
}
When I input 1, 2, 3, and 4 as my values, the graph displays the following: https://puu.sh/weGuX/3000d456bb.png
Any suggestions as to why this would be would be much appreciated, thank you.
NUMBER in UCanAccess DDL maps to the Currency field type in Access, while in the Access UI the default "Number" type is "Long Integer". If you want to create a long integer column then use the DDL keyword LONG.

Checking if username exists in MySQL Java

I have a register dialog that implements an action listener. If a user enters a name and it already exists, I want to print a message on the console. If the username does not exist, MySQL should add it into the database. Unfortunately this code won't work:
private void regButtonActionPerformed(java.awt.event.ActionEvent evt) {
if(!userBox.getText().equals(""))
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/genx", "root", "Warlock1989");
Statement stmt = con.createStatement();
String query = "SELECT name FROM accounts";
ResultSet rs = stmt.executeQuery(query);
while(rs.next())
{
String uname = rs.getString("name");
if(!uname.equals(userBox.getText()))
{
PreparedStatement pstmt = con.prepareStatement("INSERT INTO accounts(name) VALUES(?)");
pstmt.setString(1, userBox.getText());
pstmt.executeUpdate();
System.out.println("Username " + userBox.getText() + " has been registered.");
}
else
{
System.out.println("Username " + userBox.getText() + " already exists.");
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
Your current approach loads all records from database and tries to find the user which will cause memory exceptions if the database consists of huge records. So,
Do not fetch all records from database rather simply run the query using where name=? to check user already exists in the database as shown below:
PreparedStatement pstmt1 = null;
PreparedStatement pstmt2 = null;
ResultSet rs = null;
try {
String userInput = userBox.getText();
String query = "SELECT name FROM accounts where name=?";
pstmt1 = con.preparedStatement(query);
pstmt1.setString(1, userInput);
rs = pstmt1.executeQuery();
if(rs.next()) {
pstmt2 = con.prepareStatement("INSERT INTO accounts(name) VALUES(?)");
pstmt2.setString(1, userInput);
pstmt2.executeUpdate();
System.out.println("Username " + userInput + " has been registered.");
} else {
System.out.println("Username " + userInput + " already exists.");
}
} catch(SQLException sqlexe) {
//add logging
} finally {
if(pstmt1 != null)
pstmt1.close();
if(pstmt2 != null)
pstmt2.close();
if(rs != null)
rs.close();
}
Your current code does not release the resultsset & preparedstatement objects, so ensure that you are releasing the resources in the finally block.

How to pass variables into SQLite in java

I'm trying to create a SQLite for my game, and its working fine until I try to put some variables in the table HighScores.
If I try to put a variable it only works if I delete the "NOT NULL".
public void SQLite(){
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
stmt = c.createStatement();
String sql = "CREATE TABLE HighScores " +
"(ID INT PRIMARY KEY NOT NULL," +
" POINTS INT NOT NULL, " +
" NAME CHAR(50) NOT NULL, " +
" TIME INT NOT NULL, " +
" LEVEL INT NOT NULL)";
stmt.executeUpdate(sql);
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql2 = "INSERT INTO HIGHSCORES (ID,POINTS,NAME,TIME,LEVEL) " +
"VALUES (1, ?, 'rodrigo', 99, 1 );";
PreparedStatement ps = c.prepareStatement(sql2);
ps.setInt(1, 5);
stmt.executeUpdate(sql2);
stmt.close();
c.commit();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
}
Opened database successfully.
java.sql.SQLException: NOT NULL constraint failed: HighScores.POINTS
You are calling executeUpdate on stmt instead of the prepared statement. Since sql2 does not have any value for POINTS, it try to insert null hence the exception.
Change :
stmt.executeUpdate(sql2);
to
ps.executeUpdate();

Categories

Resources