How to populate TableView in JavaFX using alias - sqlite

While using swing everything works just fine.
String sql= "SELECT idrepair as '№',"
+ "case when repairStatus in (0) then 'Not Done' "
+ "when repairStatus in (1) then 'Closed' "
+ "when repairStatus in (2) then 'Open' "
+ "else 'Unknown' end as 'Status'"
+ "FROM repairjournal";
I just want new UI using JavaFX, so here is my code, i would say my efforts:
private void loadTableViewRepList(ObservableList oblist, Connection conn, TableView table) {
oblist.clear();
try {
String sql = "SELECT * FROM repairjournal";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
oblist.add(new ModelTableRepairList(
rs.getString("idrepair"),
rs.getString("case when repairStatus in (0) then 'Not Done' "
+ "when repairStatus in (1) then 'Closed' "
+ "when repairStatus in (2) then 'Open' "
+ "else 'Unknown' end ")
));
}
table.setItems(oblist);
} catch (SQLException ex) {
Logger.getLogger(RepairListController
.class.getName()).log(Level.SEVERE, null, ex);
}
}
or
private void loadTableViewRepList(ObservableList oblist, Connection conn, TableView table) {
oblist.clear();
try {
String sql = "SELECT idrepair,
case when repairStatus in (0) then
'Not Done.' when repairStatus in (1) then
'Closed' when repairStatus in (2) then 'Open'
else 'Unknown' end as 'Status' FROM repairjournal";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
oblist.add(new ModelTableRepairList(
rs.getString("idrepair"),
rs.getString("repairStatus")
));
}
table.setItems(oblist);
} catch (SQLException ex) {
Logger.getLogger(RepairListController
.class.getName()).log(Level.SEVERE, null, ex);
}
}
Main error is no such column: 'repairStatus'
Any ideas how to fix this? Yes i can rename data, but i have more tables with such data in DB.

Related

JavaFX delete datarow in tableview and sqlite

I would like to delete a row in tableview but also in the
underlying SQLite Database which populate the tableview
Here I get the selectedRow
public void deleteDBRow() {
if (tableV.getSelectionModel().getSelectedItem() != null) {
Bew selBew = tableV.getSelectionModel().getSelectedItem();
System.out.println(selBew.getName());
}
}
and can delete it with casual code
DELETE FROM Table WHERE name = ""+selBew.getName()");
But I would like to delete the entry in the sqlite database also
From time to time I have rows with the same text in every column - so this way
was critical - can I use rowID to delete the selected row in sqlite?
Here one try from me to get rowid in tableview
ObservableList bewList = FXCollections.observableArrayList();
try {
String sql = "SELECT rowID, Name, Date, Action, Info FROM tab1";
Connection conn = DriverManager.getConnection("jdbc:sqlite:TestB1.db");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
bewList.add(new Bew(rs.getInt("rowID"), rs.getString("name"), rs.getString("date"),
rs.getString("action"), rs.getString("Info")));
System.out.println("rs.next : " + rs.getInt("rowID") +" - " + rs.getString("date") +" " +
rs.getString("action") +" " + rs.getString("Info"));
}
}catch (Exception e) {
System.out.println("SQLiteDB.getData ---> Error RS");
System.err.println("*E"+e.getClass().getName() + ": " + e.getMessage());
}
return bewList;
String sql = "CREATE TABLE IF NOT EXISTS tab1" +
"(rowID INT PRIMARY KEY," +
"NAME CHAR(50) NOT NULL ,"+
"DATE CHAR(15) ,"+
"ACTION CHAR(50) ,"+
"INFO CHAR(3));";
conn.createStatement().executeUpdate(sql);
rowID ist always 0 - don't know why ???
edit:
Controller
ObservableList bewList = DB.getData();
tableV.setItems(bewList);
Edit:
Maybe error in here - add data
i add 4 values - rowid missing??
public void add(String Name, String Date, String Action, String Info) {
try {
Connection conn = DriverManager.getConnection("jdbc:sqlite:TestB2.db");
stmt = conn.createStatement();
String ValStr = "\'"+Name+"\' ,\'"+Date+"\',\'"+Action+"\' ,\'"+Info+"\'";
String sql = "INSERT INTO tab1 (rowID, NAME,DATE,ACTION, INFO) VALUES ("+ValStr+")";
// System.out.println("Button Click add"+conn.createStatement().toString());
stmt.executeUpdate(sql); //geändert
ObservableList<Bew> list = getData();
conn.close();
System.out.println("DB ROW add");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}

SQLITE JDBC driver prepared statement fails (internal pointer 0)

SQLite JDBC driver version 3.21.0 (the latest).
Summary
A prepared statement is opened for multiple insert operations on a table, but is unable to survive primary key violations.
If one "bad" insert fails due to a Primary Key violation, the prepared statement is unable to process subsequent "good" inserts. An exception "statement is not executing" is raised when calling pstmt.setString().
Tracing the error into org.Sqlite.core.CorePreparedStatement the call is failing in checkOpen() pointer==0.
Example is below.
Does anyone know why this is happening? I see a similar bug report was raised but supposedly fixed.
Connection conn = DriverManager.getConnection("jdbc:sqlite:./test.db");
String createtable = "CREATE TABLE dummy(ID text, VAL text, PRIMARY KEY(ID) )";
String psSQL = "INSERT INTO dummy (ID, VAL) VALUES (?,?)";
String id = "123456789";
String val = "FooBar";
String id2 = "123456789";
String val2 = "FooBar2";
String id3 = "345678901";
String val3 = "FooBar3";
try {
Statement st= conn.createStatement();
st.executeUpdate(createtable);
PreparedStatement pst = conn.prepareStatement(psSQL);
// 1 insert good entry
pst.setString(1, id);
pst.setString(2, val);
pst.executeUpdate();
System.out.println("1st insert OK for " + id);
// 2. try to insert bad duplicate entry with pkey violation
try {
pst.setString(1, id);
pst.setString(2, val);
pst.executeUpdate();
System.out.println("2nd insert OK for " + id);
} catch (SQLException e) {
System.out.println("2nd insert Failed for " + id);
e.printStackTrace();
}
// 3. try to insert 3rd good value
try {
pst.setString(1, id3); // exception raised here
pst.setString(2, val3);
pst.executeUpdate();
System.out.println("3 insert OK for " + id3);
} catch (SQLException e) {
System.out.println("3 insert Failed for " + id3);
e.printStackTrace();
}
pst.close();
st.executeUpdate(droptable);
} catch (SQLException e) {
e.printStackTrace();
}
This bug has been fixed in sqlite-jdbc version 3.25.2, see https://github.com/xerial/sqlite-jdbc#news.

Get all records with timestamp between current day

I want to get all records with timestamp of a current day. According to [this][1] I creating query
SELECT *
FROM table
WHERE timestamp BETWEEN date('now', 'start of day', 'localtime', 'unixepoch') AND
date('now', 'start of day','+1 day', 'localtime', 'unixepoch')"
but allways got nothing. I updating some records calling System.currentTimeMillis()/1000 function. I try without unixepoch parameter but still got nothing
EDIT: I paste my code I try to set timestamp column with diffrent types but it doesnt help too mutch
private static final String DATABASE_CREATE = "create table if not exists "
+ TABLE_DAILY_CHALLENGES +
"(" + DAILY_CHALLENGES_ID + " integer primary key autoincrement, " +
DAILY_CHALLENGES_TITLE + " text not null, "+
DAILY_CHALLENGES_CONTENT + " text not null, "+
DAILY_CHALLENGES_COUNTER + " text not null, "+
DAILY_CHALLENGES_SORT+ " integer not null, " +
DAILY_CHALLENGES_ACTUAL_COUNTER+ " text not null, " +
DAILY_CHALLENGES_TIMESTAMP+ " integer DEFAULT 0, " +
DAILY_CHALLENGES_FINISHED+ " integer DEFAULT 0, " +
DAILY_CHALLENGES_TYPE + " text not null);";
private static Database getDbHandlerInstance(){
if(dbHandler==null){
return init();
}else
return dbHandler;
}
private static Database init(){
dbHandler = DatabaseFactory.getNewDatabase(DATABASE_NAME,
DATABASE_VERSION, DATABASE_CREATE, null);
dbHandler.setupDatabase();
try {
dbHandler.openOrCreateDatabase();
dbHandler.execSQL(DATABASE_CREATE);
} catch (SQLiteGdxException e) {
e.printStackTrace();
}
try { //TODO:: make it more efficient
String query="SELECT * FROM dailyChallenges";
DatabaseCursor cursor = dbHandler.rawQuery(query);
if(cursor.getCount()!=NUMBERS_OF_RECORDS){
cleanTable();
populateDatabase();
}
} catch (SQLiteGdxException e) {
e.printStackTrace();
}
return dbHandler;
}
private static void cleanTable() {
try {
dbHandler.execSQL("delete from "+ TABLE_DAILY_CHALLENGES);
} catch (SQLiteGdxException e) {
e.printStackTrace();
}
}
public static Challenge[] getChallenge(){
DatabaseCursor cursor=null,cursorAll=null;
Challenge[] challenge;
try {
String query="SELECT * FROM dailyChallenges WHERE timestamp BETWEEN date('now', 'start of day', 'localtime', 'unixepoch') AND date('now', 'start of day','+1 day', 'localtime', 'unixepoch')";
cursor = getDbHandlerInstance().rawQuery(query);
} catch (SQLiteGdxException e) {
e.printStackTrace();
}
//create new challenge
if(cursor.getCount()!=0){
//logic,cursor.getCount() is always 0}

Delete from command not working in sqlite?

I have a sqlite db file. I am using DB Browser for Sqlite as the client. I went in and ran delete from command on most of my tables. Thereafter I tried to export using the option Database to SQL file I notice all my data is appearing in it. What I wondering is that why the data have not been deleted? I know the sqlite file size will not shrink.
Below is snippet of my codes.
string str = #"Data Source=" + userFilePath + "\\mysqlite.sqlite3";
using (SQLiteConnection con = new SQLiteConnection(str))
{
con.Open();
SQLiteTransaction trans = con.BeginTransaction();
try
{
String cmdSelect1 = "Select * from table1 where companyID='" + companyID + "' And month='" + month + "' And year='" + year + "'";
int fiscalPeriod = Convert.ToInt32(monthNumber);
int financialYear = Convert.ToInt32(itemvalueyear);
using (SQLiteCommand cmd1 = new SQLiteCommand(cmdSelect1, con, trans))
{
SQLiteDataReader dr1 = cmd1.ExecuteReader();
if (dr1.Read())
{
MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show("Records Already Exist ? Are you confirm replace it?", "Delete Confirmation", System.Windows.MessageBoxButton.YesNo);
if (messageBoxResult == MessageBoxResult.Yes)
{
String deleteTable = "Delete from table1 where companyID='" + companyID + "' And month='" + month + "' And year='" + year + "'";
using (SQLiteCommand cmdDeleteTb1 = new SQLiteCommand(deleteTable, con, trans))
{
cmdDeleteTb1.ExecuteNonQuery();
cmdDeleteTb1.Dispose();
}
foreach (object line in linesC)
{
if (line.GetType() == typeof(TypeC))
{
String cmdText2 = "INSERT INTO table1(tbID,companyID,month,year) VALUES(#tbID,#companyID,#month,#year)";
using (SQLiteCommand cmd = new SQLiteCommand(cmdText2, con, trans))
{
cmd.Parameters.AddWithValue("#tbID", tbID);
cmd.Parameters.AddWithValue("#companyID", companyID);
cmd.Parameters.AddWithValue("#month", month);
cmd.Parameters.AddWithValue("#year", year);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.Dispose();
}
}
}
}
}
dr1.Close();
cmd1.Dispose();
}
trans.Commit();
MessageBox.Show("Successfully Inserted Into Database");
}
catch (Exception ex)
{
MessageBox.Show("Rollback " + ex.ToString());
trans.Rollback();
}
con.Close();
con.Dispose();
GC.Collect();
Ok:
It appears you are beginning two transactions. You begin your loop inserts after you begin your delete.
Commit your Delete transaction and then later commit your inserts.
This is than committing after beginning both transactions.

SQLite test if record exists

I am struggling with testing if there is specific data in my SQLite database.
The method accepts a subject code, person id, and a table name. I am 100% sure those 3 things are correct.
What this should do is try to select a record. If the record can be selected return -1, otherwise return 0.
My problem is the datareader does not seem to be reading any records, when there is records in my database.
public int TestIfExists(string subID, string personID, string table)
{
_sqlConnection = new SQLiteConnection(_conStr);
bool dataRead = false;
int rc = 0;
try
{
string selectQuery = "SELECT * FROM " + table + " WHERE PersonID = '" +
personID + "' AND SubjectCode = '" + subID + "'";
_sqlConnection.Open();
SQLiteCommand sqlCommand = new SQLiteCommand(selectQuery, _sqlConnection);
IDataReader idr = sqlCommand.ExecuteReader();
dataRead = idr.Read();
if (dataRead == true)
{
rc = -1;
}//end if
else
{
rc = 0;
}//end else
idr.Close(); // Closed IDataReader
}//end try
catch (SQLiteException sqlEx) // Catch SQLiteException
{
MessageBox.Show(sqlEx.ToString());
throw new DataStoreError(sqlEx.Message);
}//end catch
catch (Exception ex)
{
throw ex;
}//end catch
finally
{
_sqlConnection.Close();
}//end finally
return rc; //Single return
}
When you are trying to see if it exists or no, you can do a
SELECT Count(*) FROM Table WHERE (...)
and this way 0 would means doesn't exists, other wise yes.

Resources