I have a DATE field in my database with format 'YYYY-MM-DD'. Now I want to extract only 'day' from that day i.e. 'DD'. My table name is 'date' and the column name where date is stored is 'lastDonated'. How do i do it... please look these codes for more details.
public String day() {
String b = "";
SQLiteDatabase db = getWritableDatabase();
String query = "???(what to place in here?)";
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
b = c.getString(c.getColumnIndex("lastDonated"));
c.moveToNext();
return b;
}
I only have one row in the database
Use this query
SELECT strftime('%d', YourDateColumn) AS SomeAlias FROM YourTable
And get the value like this
b = c.getString(c.getColumnIndex("SomeAlias"));
Reference: https://www.sqlite.org/lang_datefunc.html
Related
I have to make more than 300 selects from my database.
Each of those queries has to be called inside of a for each loop, here's an example:
for(int id : myids){
Cursor cursor = MyDatabaseHelper.runMyQuery(id);
while(cursor.moveToNext()){
//my stuff...
}
}
MyDatabaseHelper is an instance of a database helper class, the function is like this
public Cursor runMyQuery(int id){
SQLiteDatabase db = this.getWritableDatabase();
Cursor ret = db.rawQuery("select Name, Surname, Age from PTable where Id = " + id, null);
return ret;
}
I've been told that the constant "open and close" of the db because of multiple queries it the cause of my performance issues and I should, instead, make a single query (using union etc).
Changing my code to a single query would mean changing the entire database, and I was hoping not to do that.
Is there anything I can do to improve the performance and keep the multiple selects at the same time?
Thanks
I think what you are looking for is the in clause.
Convert your myids into a string. Something like
String inClause = "(1,2,3)"
and you can use it as
"select Name, Surname, Age from PTable where Id in " + inClause
You can read more of the in operator here
You can return a single Cursor containing all the rows.
First change your runMyQuery() method to this:
public Cursor runAll(String list){
SQLiteDatabase db = this.getWritableDatabase();
String sql = "select Name, Surname, Age from PTable where " + list + " like '%,' || id || ',%'"
Cursor ret = db.rawQuery(sql, null);
return ret;
}
So you pass to the method runAll() a String which is the the comma separated list of all the ids that you have in myids and with th eoperator LIKE you compare it to each id of the table.
You create this list and get the results in a Cursor object like this:
StringBuilder sb = new StringBuilder(",");
for(int id : myids){
sb.append(String.valueOf(id)).append(",");
}
String list = sb.length() > 1 ? sb.toString() : "";
if (list.length() > 0) {
Cursor c = runAll(list);
while(c.moveToNext()){
//your stuff...
}
}
I tried to calculate a report and displays the result in the texview "edt1". But it's not displayed.
there is mydatabasehelper :
public void calculrapport(Argent a)
{
db = this.getWritableDatabase();
String query = "select sum(Entree) from Argent where date between \"datedebut\" and \"datefin\" ;";
Cursor cursor = db.rawQuery(query , null) ;
int count = cursor.getCount();
}
There is my class Rapport.java :
public void onOKClick ( View v ) {
if (v.getId() == R.id.okrapport) {
EditText datedebut = (EditText) findViewById(R.id.datedebut);
EditText datefin = (EditText) findViewById(R.id.datefin);
String strdatedebut = datedebut.getText().toString();
String strdatefin = datefin.getText().toString();
Argent a = new Argent();
helper.calculrapport(a);
edt1.setText( );
}
}
Thanks in advance.
Assuming that the query works as expected (especially considering that variables used have the appropriate scope, which would appear unlikely perhaps try using select sum(Entree) from Argent to test without the complications of wheteher or not the datedebut and datefin variables can resolve and if so resolve to usable values) then you need to :-
Extract the appropriate value and return the value from the method and then use the returned value to set the text in the TextView.
To return the value the method should not be void, but have an appropriate return type (String will be used for the example),
so instead of public void calculrapport(Argent a), use public String calculrapport(Argent a) (thus the method will be required to return a string)
To extract the value the cursor needs to be moved to the appropriate row (there should only be the one row as the sum function is an aggregate function and there is only the one group (aggregate functions work on gropus) i.e. all rows)
As such the method could be :-
public String calculrapport(Argent a)
{
String rv = "0"; //<<<< used to return 0 if no rows are selected by the query
db = this.getWritableDatabase();
String query = "select sum(Entree) from Argent where date between \"datedebut\" and \"datefin\" ;";
Cursor cursor = db.rawQuery(query , null) ;
if (cursor.moveToFirst()) {
rv = cursor.getString(0); //<<<< get the value from the 1st (only) column
}
cursor.close(); //<<<< Cursors should always be closed when done with
return rv;
}
To set the TextView with the returned value instead of using :-
helper.calculrapport(a);
edt1.setText( );
Use :-
edt1.setText(helper.calculrapport(a));
Or :-
String sum = helper.calculrapport(a);
edt1.setText(sum);
Additional re comment:-
The problem is located in the SQlite query (select sum(Entree) from
Argent where date between \"datedebut\" and \"datefin\" ;) exactly
when we call "datedebut" and "datefin" taht located in the class
rapport.java
Then String query = "select sum(Entree) from Argent where date between \"datedebut\" and \"datefin\" ;";
resolves to :-
select sum(Entree) from Argent where date between "datedebut" and "datefin" ;
I believe, assuming that datedebut and datefin are string variables, and that they are in a valid SQLite date format e.g. they could be 2018-01-01 and 2018-02-01 (and that values in the date column are formatted as a valid SQLite date format) that you should instead be using :-
String query = "select sum(Entree) from Argent where date between '" + datedebut + "' and '" + datefin +"' ;";
Which would then resolve to something like :-
SELECT sum(entree) FROM argent WHERE date BETWEEN '2018-01-01' AND '2018-02-01';
For valid SQLite date formats; refer to Date And Time Functions
Note the above is in-principle code and has not been tested so may contain some simple typing errors.
I am having below table on my android sqlite database.
My Date filed is TEXT;
ID Name Date
1 ABY 2014-12-01
2 RUBY 2015-01-10
3 AMY 2015-01-15
4 ROBEN 2014-10-25
I need to sort the result like in mysql
select * from Table where YEAR(DATE)='2015';
How can I get the above result in Andorid sqlite database?
I think you want to use the LIKE operand
SELECT * FROM table WHERE Date LIKE '2015%'
http://www.tutorialspoint.com/sqlite/sqlite_like_clause.htm
Edit for query:
String selectQuery = "SELECT id, name FROM table WHERE date like \'" + "2015" + "\'";
Cursor c = db.rawQuery(selectQuery, new String[] { fileNameOfDb });
if (c.moveToFirst()) {
name = c.getString(c.getColumnIndex("name"));
}
c.close();
I have a Sqlite database that works fine, I can insert rows with no problem, but when I try to do an update only one column get updated. I get a return value of 1, but only the column SCANNED get updated, that is the only column that already had a value of 0 and was change to 1.
public int UpdateScanInvoice(String Invoice, int scanned, String empname,
int empnum) {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd",Locale.US);
String formattedDate = df.format(c.getTime());
SimpleDateFormat tf = new SimpleDateFormat("hh:mm:ss",Locale.US);
String formattedTime = tf.format(c.getTime());
String strFilter = MySQLiteHelper.TICKETNR + "='" + Invoice +"'";
ContentValues scanvalues = new ContentValues();
scanvalues.put(MySQLiteHelper.LOADEMPNAME, empname);
scanvalues.put(MySQLiteHelper.SCANNED, scanned);
scanvalues.put(MySQLiteHelper.LOADEMPNUM, empnum);
scanvalues.put(MySQLiteHelper.LOADDATE,formattedDate);
scanvalues.put(MySQLiteHelper.LOADTIME, formattedTime);
SQLiteDatabase db = dbHelper.getWritableDatabase();
int rowUpdated = db.update(MySQLiteHelper.TABLE_INVOICE, scanvalues,strFilter, null);
return rowUpdated;
}
Maybe my original insert is wrong?
This is the original insert.
values.put(MySQLiteHelper.SCANNED, 0);
values.put(MySQLiteHelper.LOADDATE, "");
values.put(MySQLiteHelper.LOADTIME, "");
values.put(MySQLiteHelper.LOADEMPNAME, "");
values.put(MySQLiteHelper.LOADEMPNUM, "");
I the file has 19 columns and only the last 4 will not update or take any value when I do an insert.
I deleted the data recreated the database, same result.
Thanks,
KimHJ
Why are you again updating all the values You want to change the SCANNED value for that just update that value only like this..
scanvalues.put(MySQLiteHelper.SCANNED, scanned);
SQLiteDatabase db = dbHelper.getWritableDatabase();
int rowUpdated = db.update(MySQLiteHelper.TABLE_INVOICE, scanvalues,strFilter, null);
for updating only SCANNED this is enough but you are updating all the values..this will replace your all old data
Can someone help me and tell me what's wrong here?
String date = "Samstag, 30.7.2011";
myDB = this.openOrCreateDatabase(MY_DB_NAME, MODE_PRIVATE, null);
String load = "SELECT db_scheine FROM ZahlenUndDatum where db_datum= "+date+"";
Cursor c = myDB.rawQuery(load, null);
String test = c.toString();
Log.d("output", test);
I would like to search for the date in the database and then return the value of the record from db_scheine.
try adding moveToFirst()
Cursor c = myDB.rawQuery(load, null);
c.moveToFirst();
String test = c.toString();
The rawQuery() method, will create a cursor, which is initially placed before the first row. So you can do something like this:
Cursor c = myDB.rawQuery(load, null);
while(c.moveToNext()) {
// do stuff
}
Without skipping the first row :)
UPDATE:
Your date is giving problems as well, im guessing the db_datum field is a string, enclose the string in quotes like so:
String load = "SELECT db_scheine FROM ZahlenUndDatum WHERE db_datum= '"+date+"'";