jdbc: get date from sqlite database - java

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.

Related

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.

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();

Java SQLite database, insert entry giving nullPointerException

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);

java.sql.SQLException: lock wait time out exceeded; try restarting transaction

Hi in my project i am have created 2 tables which was Role_header and Role_details tables.
And also Role_details table is referring to the Role_header table.
In my java class i have two method they are
insertRoleHeader(...) --> which will be called first and set conn.setAutoCommit(false).i didn't commit this because following this i want to insert role_details with multiple records in Role_details table. so i will call this method first, if any exceptions thrown. i have set this to rollback in catch.
insertRoleDetails(.....) --> this method will be called by forloop. each and every calling of this method i will commit. at that time i am getting error as java.sql.SQLException: lock wait time out exceeded; try restarting transaction.
my sample code is here:
public void insertHeader(RoleMasterSupport rMS) throws SQLException {
connectDB();
Statement stmt = null;
try {
roleMasterConn.setAutoCommit(false);
stmt = roleMasterConn.createStatement();
String sql = "insert into role_header( create_user, " +
"create_date, " +
"run_user, " +
"run_date, " +
"role_id, " +
"role_name, "+
"remarks) " +
"values('"+Constants.sUserName+"', now(), "
+ "'"+Constants.sUserName+"', now(), "
+ "'"+rMS.getsRoleID()+"', '"+rMS.getsRoleName()+"', "
+ "'"+rMS.getsRemarks()+"') ";
stmt.executeUpdate(sql);
stmt.close();
} catch (SQLException e) {
roleMasterConn.rollback();
throw e;
}
}
public void insertDetails(RoleMasterSupport rMS, TableModel model) throws SQLException
{
for (int i = 0; i < model.getRowCount(); i++) {
dbop.insertDetail(rMS, rMS.getaLScreenNames().get(i),
rMS.getaLAdd().get(i), rMS.getaLView().get(i),
rMS.getaLModify().get(i), rMS.getaLDelete().get(i));
}
}
public void insertDetail(RoleMasterSupport rMS, String sScreenName, String sAdd, String sView, String sModify, String sDelete) throws SQLException
{
connectDB();
Statement stmt = null;
try {
roleMasterConn.setAutoCommit(false);
stmt = roleMasterConn.createStatement();
String sql = "insert into role_details( create_user, " +
"create_date, " +
"run_user, " +
"run_date, " +
"role_id, " +
"screen_name, " +
"modify_screen, " +
"add_screen, " +
"delete_screen, " +
"view_screen) " +
"values('"+Constants.sUserName+"', now(), "
+ "'"+Constants.sUserName+"', now(), "
+ "'"+rMS.getsRoleID()+"', '"+sScreenName+"', "
+ "'"+sModify+"', '"+sAdd+"', "
+ "'"+sDelete+"', '"+sView+"') ";
stmt.executeUpdate(sql);
roleMasterConn.commit();
} catch (SQLException e) {
roleMasterConn.rollback();
throw e;
}
}

Categories

Resources