I have a table and I want to get a specific item from it.
For example the statement :
"SELECT password FROM "+tableName+" WHERE username='"+username+"'";
How can I use that statement and get the string value of the password I asked for?
(I was able to get the curser but I couldn't get from it the string value of it)
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = null;
String sql ="SELECT password FROM "+tableName+" WHERE username='"+username+"'";
cursor= db.rawQuery(sql,null);
String checked = cursor.getString(3);
if(checked.equals(password)){
return true;
}else{
return false;
}
The problam is with the line:
String checked = cursor.getString(3);
Any suggestions?
I suggest to use this
cursor.getString(cursor.getColumnIndex("column name"));
Best regards
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'm writing an android application and I need to search the data base, this is the method I use:
public Cursor getData(String table, String keyword, SQLiteDatabase db){
String selection;
Cursor cursor;
switch (table){
case "User":
String [] projection = {id,name,phone};
selection = "username LIKE ?";
String [] selection_arg = {keyword};
cursor = db.query("User",projection,selection,selection_arg,null,null,null);
break;
//omitted
default:
return null;
}
return cursor;
The user put in the keyword
keyword = search_user.getText().toString();
Cursor cursor = dbHelper.getData(ShippingApplication.User.USER_TABLE,keyword,db);
The code does not work, when I debug, I see the mQuery of the db variable is:
SQLiteQuery: SELECT userID, userName, phoneNumber FROM User WHERE userName LIKE ?
It looks like the query does not pass the value of the keyword in to the sql command.
Could someone tell me what's wrong?
EDIT 2: I change the code a little bit and now it works:
String selection = ShippingApplication.User.name + " LIKE '%" + keyword + "%'";
Cursor cursor = db.query(The table name,projection,selection,null,null,null,null);
try this way
please check your SQLiteDatabase object is not null
after that check Table is created or not
i get the cursor count i already debug it and it's working fine for me
public Cursor getData(String table, String keyword, SQLiteDatabase db){
String selection;
Cursor cursor;
switch (table){
case "Tbl_staticContent":
String [] projection = {"PageTitle","Content"};
selection = "PageTitle LIKE ?";
String [] selection_arg = {keyword};
cursor = db.query("Tbl_staticContent",projection,selection,selection_arg,null,null,null);
Log.e("count",""+cursor.getCount());
//I have create table and stored data and also check the like condtion also it's work fine and get the cursor.getCount() > 0 also .
break;
default:
return null;
}
return cursor;
}
I have two table in my sqlite db here is the first table named supplier and here is the second table named product
what I want to do is I want to get the supplier_name in table product by selecting id_supplier in table_product. Here is my query SELECT table_supplier.id_supplier, table_supplier.supplier_name from table_invoice_in, table_supplier where table_invoice_in.id_product = '4' and table_supplier.id_supplier = table_invoice_in.id_supplier
and what I got from that query is I can get the id_supplier but supplier_name gives me 0 value, but when I try the query in mysql, I got the correct result. My question is :
Is this a limitation of sqlite or there are something wrong with my query?
Thank you in advance.
Try using a JOIN:
SELECT table_supplier.id_supplier, table_supplier.supplier_name FROM table_supplier JOIN table_invoice_in ON table_supplier.id_supplier = table_invoice_in.id_supplier WHERE table_invoice_in.id_product = '4'
The problem solved! When we try to query some column(s) from multiple table, make sure that we get the desired result by pointing directly to the column name. Here is my correct code
public Cursor SelectInvoiceInById(String id){
String query = "SELECT product_name from table_product, table_invoice_in where table_invoice_in.id_invoice_in = '"+ id + "' and table_product.id_product = table_invoice_in.id_product";
ReadDB();
cursor = database.rawQuery(query, null);
cursor.moveToFirst();
if(cursor.getCount() > 0){
while (!cursor.isAfterLast()){
Log.d("RESULT", String.valueOf(cursor.getString(cursor.getColumnIndex(SQLiteHelper.PRODUCT_NAME))));
cursor.moveToNext();
}
}
CloseDB();
return cursor;
}
I am facing an issue in inserting an issue in inserting a text with single quotes in sqlite db in android. it is returning the following error.
06-21 15:21:55.644: E/AndroidRuntime(16328): android.database.sqlite.SQLiteException: near
"re": syntax error (code 1): , while compiling: select * from tbl_chatHistory where
chat_date = '1.403344315631E12' and chat_time = '1.403344315635E12' and chat_text =
'you're'
Please help.
**************** EDITED *************************
public boolean checkChatExists(String date, String time, String chat) {
boolean result = false;
String selectQuery = "select * from tbl_chatHistory where chat_date = '"+date+"'
and chat_time = '"+time+"' and chat_text = '"+chat+"'";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
result = true;
} else {
result = false;
}
cursor.close();
return result;
}
In SQL string literals you can escape ' as ''.
It however better to use parametrized queries. Replace the string literals with ? and provide the values in the bindArgs array. For example:
String selectQuery = "select * from tbl_chatHistory where chat_date = ? and chat_time = ? and chat_text = ?";
Cursor cursor = database.rawQuery(selectQuery, new String[] { date, time, chat });
Use ` instead of '. The problem is that the second ' is recognised as the end of the text.
I want to search a particular string in the whole database table and get the row details of the matched column. For example I am having the table as like below
**name email address designation**
sai xy#mail 75385 nagar
thiru y#mail 75893 city
Now I am having the searching key like "nagar" or "thiru" how can prepare a query for it. if any one knows Please help me. Thanks in advance.
Read the whole table into a cursor and search in each column to get column name.
May be like this:
private String getColumnName(String key){
String columnName="";
DataBaseAdapter dba=new DatabaseAdapter(getApplicationContext());
dba.open();
Cursor cr=dba.fetchAllData();
cr.moveToFirst();
while(!cr.isAfterLast()){
if(key.equals(cr.getString(cr.getColumnIndex("name")))){
columnName="name";
}
cr.moveToNext();
}
cr.moveToFirst();
while(!cr.isAfterLast()){
if(key.equals(cr.getString(cr.getColumnIndex("email")))){
columnName="email";
}
cr.moveToNext();
}
cr.moveToFirst();
while(!cr.isAfterLast()){
if(key.equals(cr.getString(cr.getColumnIndex("address")))){
columnName="address";
}
cr.moveToNext();
}
cr.moveToFirst();
while(!cr.isAfterLast()){
if(key.equals(cr.getString(cr.getColumnIndex("designation")))){
columnName="designation";
}
cr.moveToNext();
}
return columnName;
}
fetchAllData() function in DataBaseAdapter class contains following code:
public Cursor fetchAllData(){
try {
return database.query(TABLENAME, null, null, null, null,
null, null);
} catch (Exception e) {
return null;
}
}
This will give column name of your key.
So now it's easy to run query like this:
String query= "SELECT * FROM tablename where "+getColumnName()+"='"+key+"'" ;
try this query..
SELECT * FROM tablename WHERE name = 'nagar' or email = 'nagar' or address = 'nagar' or designation = 'nagar';
or
SELECT * FROM tablename WHERE name or email or address or designation = 'nagar';