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}
Related
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());
}
}
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.
I am getting the error as:
Error Code : 1 (SQLITE_ERROR)
Caused By : SQL(query) error or missing database.
(near "EXISTSnotes": syntax error (code 1): , while compiling: CREATE TABLE IF NOT EXISTSnotes(idINTEGER PRIMARY KEY,titleTEXT,descriptionTEXT)).
Need help.
public DatabaseHandler(Context context) {
super(context, DatabaseValues.DATABASE_NAME, null, DatabaseValues.DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) { db.execSQL(DatabaseValues.TABLE_NOTES_CREATE); }
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DatabaseValues.TABLE_NOTES_DROP);
onCreate(db);
}
public void addNote(Note note) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues noteValues = new ContentValues();
noteValues.put(DatabaseValues.NOTES_TITLE, note.getTitle());
noteValues.put(DatabaseValues.NOTES_DESCRIPTION, note.getDescription());
db.insert(DatabaseValues.TABLE_NOTES, null, noteValues);
db.close();
}
public void updateNote(Note note) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues noteValues = new ContentValues();
noteValues.put(DatabaseValues.NOTES_TITLE, note.getTitle());
noteValues.put(DatabaseValues.NOTES_DESCRIPTION, note.getDescription());
db.update(DatabaseValues.TABLE_NOTES, noteValues, DatabaseValues.NOTES_ID + "= ?",
new String[]{String.valueOf(note.getId())});
db.close();
}
public void deleteNote(String id) {
SQLiteDatabase db = this.getWritableDatabase();
String deleteQuery = "DELETE FROM" + DatabaseValues.TABLE_NOTES + "WHERE" + DatabaseValues.NOTES_ID + "= '" + "id" + "'";
db.execSQL(deleteQuery);
db.close();
}
public List<Note> getAllNotes() {
List<Note> notes = new ArrayList<>();
SQLiteDatabase db=this.getReadableDatabase();
String selectQuery = "SELECT * FROM" + DatabaseValues.TABLE_NOTES;
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Note note = new Note();
note.setId(Integer.parseInt(cursor.getString(0)));
note.setTitle(cursor.getString(1));
note.setDescription(cursor.getString(2));
notes.add(note);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return notes;
}
}
The error seems to be clear enough to see what's going on:
while compiling: CREATE TABLE IF NOT EXISTSnotes(idINTEGER PRIMARY KEY,titleTEXT,descriptionTEXT)).
Your query for creating the Db seems to be missing a whitespace between 'EXISTS' and the table name 'note'.
UPDATE
You are actually missing many more whitespace. Format your query like this and make sure all others query you build have the correct whitespacing or they will fail as well.
public static final String TABLE_NOTES_CREATE = "CREATE TABLE IF NOT EXISTS " + TABLE_NOTES + " (" + NOTES_ID + " INTEGER PRIMARY KEY," + NOTES_TITLE + " TEXT," + NOTES_DESCRIPTION + " TEXT)";
i have a spinner filled with value (category from category table) from sqlite now i need a select query to retrieve items into listView. such that on spinner selection change listview values also change . items are coming from another table (items).cid is foreign key in items table and cid is primary key in category table i tried this but showing empty listview....
String select = "SELECT " +
Support.KEY_INAME + " FROM "
+ Support.TABLE_ITEMS + " LEFT JOIN "
+ Support.TABLE_CAT + " ON "
+ (Support.TABLE_ITEMS + "." + Support.KEY_CID) +" = "
+ (Support.TABLE_CAT + "." + Support.KEY_CID)
+ " WHERE " + Support.TABLE_CAT + "." + Support.KEY_CID + " =?";
this is my spinner selection and loading listview data code...
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, final int position, long id) {
Spinner spinner = (Spinner)parent;
if (spinner.getId() == R.id.spinner1) {
dbRepo = new DBRepo(getApplicationContext());
final List<Support> list = dbRepo.getItems1();
adapter = new Custom(Category.this, R.layout.view_entry, list);
adapter.setDropDownViewResource(android.R.layout.simple_list_item_1);
adapter.notifyDataSetChanged();
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setAdapter(adapter);
}
the above query is true and alternatively i solve my problem using these two queries
String selectQuery = "SELECT * FROM " + TABLE_ITEM + " WHERE " + KEY_CID + " ='" + cid + "'";
Cursor c = db.rawQuery(selectQuery, null);
OR
Cursor c = db.rawQuery("SELECT * FROM item_table WHERE _CategoryID =? " ,new String[]{cid}, null );
and change also change the code spinner.setonItemSelected like this
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
handler = new DBSQLite(getBaseContext());
String selected = (String) parent.getItemAtPosition(position);
// Toast.makeText(getApplicationContext(), selected, Toast.LENGTH_SHORT).show();
String cid = handler.getCid(selected);
final ArrayList<Support> item = handler.getItems(cid);
adapter = new CustomAdapter(AvailableItems.this, R.layout.available_view, item);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
I am passing xml to a stored procedure and it is compiling but no row inserted into the database.
My code
foreach (int item in objDirectory.PhotoId)
{
//roots = roots + "<row DirectoryId='"+objDirectory.DirectoryId+"'PhotoId='" +item+"'CreatedBy='"+"Admin"+"'ModifiedBy='"+"Admin"+"'/>";
roots = roots + "<row DirectoryId= '" + objDirectory.DirectoryId + "' PhotoId='" + item + "' CreatedBy ='" + "Admin" + "' ModifiedBy ='" + "Admin" + "'/>";
}
PhotoIds = string.Format(PhotoIds, roots);
objDirectory.SavePhotoId(PhotoIds);
Save Method
public void SavePhotoId(string PhotoId)
{
SqlTransaction tran = null;
try
{
SqlParameter[] arParams = new SqlParameter[3];
m_objConn = new SqlConnection(m_strConn);
m_objConn.Open();
tran = m_objConn.BeginTransaction();
arParams[0] = new SqlParameter("#PhotoID", PhotoId);
SqlHelper.ExecuteNonQuery(tran, CommandType.StoredProcedure, "InsertUpdatePhotIdInAlbum", arParams);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (m_objConn.State == ConnectionState.Open)
{
m_objConn.Close();
m_objConn = null;
}
}
}
Stored procedure:
CREATE Procedure [dbo].[InsertUpdatePhotIdInAlbum]
#PhotoID xml=null
As
Begin
set nocount on;
if #PhotoID IS NULL
Begin
Return;
End
Declare #PhotoAlbumDetail TABLE (AlbumID int, PhotoId int, CreatedBy varchar(50),
ModifiedBy varchar(50))
insert into #PhotoAlbumDetail(AlbumID, PhotoID, CreatedBy, ModifiedBy)
select
t.c.value('./#DirectoryId', 'int') as AlbumID,
t.c.value('./#PhotoId', 'int') as PhotoID,
t.c.value('./#CreatedBy', 'varchar(50)') as CreatedBy,
t.c.value('./#ModifiedBy', 'varchar(50)') as ModifiedBy
from
#PhotoID.nodes('/root/row') t(c);
INSERT INTO [dbo].[tbl_PhotoAlbumDetail](AlbumID, PhotoId, CreatedBy, ModifiedBy)
SELECT
p.AlbumID, p.PhotoId, p.CreatedBy, p.ModifiedBy
FROM
#PhotoAlbumDetail p
End