I used a code similar to the following code to search the database person name :
cursor.query(select column from Table where column_person_Name="John");
But now I want to search the names of a few people together,How to do it?
The way to do that using SQlite would be using IN:
SELECT * FROM persons WHERE name IN ("John", "Doe");
In Java, having an array of Strings, you could do it like that:
final String[] namesArray = {"John", "Doe"};
// Pad the Strings with quotes: John -> 'John'
for (int i = 0; i < namesArray.length; i++) {
namesArray[i] = "'" + namesArray[i] + "'";
}
// Join the Strings: 'John', 'Doe'
final String names = TextUtils.join(",", namesArray);
final String query = "SELECT * FROM persons WHERE name IN ("+names+")";
This results in:
SELECT * FROM persons WHERE name IN ('John','Doe')
You can use IN condition
SELECT *
FROM Table
WHERE column_person_Name IN ('Name1', 'Name2', 'Name3');
By using the OR operator;
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
here an example;
cursor.rawQuery("select column from Table where column_person_Name='John' OR column_person_Name='Bob');
Other solution for your problem can be, use like Keyword, where you get multiple results based on the search.
Like is used across application partial known data.
SELECT
column_list
FROM
table_name
WHERE
column_1 LIKE %yoursearch_word%;
Room supports Collections as a query argument.
Query in Room is like:
#Query("SELECT first_name, last_name FROM user WHERE region IN (:regions)")
public List<NameTuple> loadUsersFromRegions(List<String> regions);
Check official guides.
Related
I am building my first android app where I am trying to sync mysql data to sqlite in android. I have two tables in mysql and both gets synced properly into android sqlite. The first table is as follows:
id ProjectName
1 RA_Tesco
2 RA_Coors
3 RA_JWNT
The second table is as follows:
id pid Outlet Add1
1 1 Tesco XYZ
2 1 Tesco ABC
3 2 Coors NBC
The PID in second table references to id of first table. How can I subset the second table based on PID value derived from id of first table. I know it is pretty straight forward in php or mysql or even in Python or R. However, fetching the id based on string and referencing the same in the second table seems quite tricky in Android. My codes so far:
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
clickedId = getIntent().getExtras().get("clickedId").toString();
When I toast clickedId, I get the correct string, for example, RA_Tesco.
cursor = sqLiteDatabase.rawQuery("SELECT * FROM "+SQLiteHelper.TABLE_NAME1+" where pid = 1"+"", null);
The above code also renders the correct set of records from the sqlite table. I am struggling with integrating them both. I tried the following:
String pid;
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
clickedId = getIntent().getExtras().get("clickedId").toString();
pid = sqLiteDatabase.rawQuery( "select id from "+sqLiteHelper.TABLE_NAME+" where projectName = "+clickedId+"", null );
I am getting incompatible types error.
This is what worked for me:
clickedId = getIntent().getExtras().get("clickedId").toString();
cursor = sqLiteDatabase.rawQuery("SELECT * FROM "+SQLiteHelper.TABLE_NAME1+" where pid = (select id from "+SQLiteHelper.TABLE_NAME+ " where ProjectName = '"+clickedId+"'"+")", null);
I just followed the same MySQL principle of nesting queries. The above code roughly reads as follows:
select * from table2 where pid = (select id from table1 where projectname="xyz");
1) Try put your query to single quote
2) rawQuery returns Cursor, not String
So,
Cursor pidCursor = sqLiteDatabase.rawQuery( "select id from "+sqLiteHelper.TABLE_NAME+" where projectName = '"+clickedId+"'", null );
If you want to get the corresponding rows from the 2nd table when you pass as an argumnent the value of a ProjectName (I guess this is clickedId although its name is id?), create a statement like this:
String sql =
"select t2.* from " + SQLiteHelper.TABLE_NAME1 +
" t2 inner join " + SQLiteHelper.TABLE_NAME +
" t1 on t1.id = t2.pid where t1.ProjectName = ?";
This joins the 2 tables and returns all the columns of the 2nd table.
The execute rawQuery() by passing clickedId as a parameter, which is the proper way to avoid sql injection:
Cursor cursor = sqLiteDatabase.rawQuery(sql, new String[] {clickedId});
I have a query that joins 2 tables get the required data on my android, what picture here is the user clicks on an item and the item's ID is used to query the right data in the Database, I know I can simply use database.query() but it according to my research it is used for simply database querying only, in my case I should use rawQuery() which provides more power of the database. below is my query which links table 1 to table 2 to get the users name from table one and user last name from table 2 if the foreign key is the same as user key
Assume this is my query:
String sQuery = SELECT table1.ID, table2.userlastname FROM table1, table2 WHERE "+table1.ID = table2.foreign;
If i try to specify the user id like below it gets all data in the database table which means i should replace id with "=?" but how do I do this when I am dealing which such a query, one that uses db.rawQuery() instead of db.query()
`private Object userInfo(int id)
{
String sQuery = SELECT table1.ID, table2.userlastname
FROM table1, table2 WHERE "+table1.ID = id;
}`
Basically you replace the parameter by question marks '?' and pass them through a String array in the order they appear in the query.
String queryStr = "SELECT table1.ID, table2.userlastname
FROM table1
INNER JOIN table2 ON table1.ID = table2.foreign;
WHERE table1.ID = ?";
String[] args = new String[1];
args[0] = String.valueOf(id);
Cursor cur = db.rawQuery(queryStr, args);
it did not work until I joined table 2 like:
`String queryStr = "SELECT table1.ID, table2.userlastname
FROM table1
INNER JOIN table2 ON table1.ID = table2.foreign
WHERE table1.ID = ?";
String[] args = new String[1];
args[0] = String.valueOf(id);
Cursor cur = db.rawQuery(queryStr, args);`
I am trying to explore android and I just started using SQLite database. I'm wondering on what is the right syntax for selecting a single row from a table, where the row I want to select is from the value entered from a user using editText. Thanks in advance.
I'm going to disagree with both of the answers above. What if the user enters this query:
Bobby Tables'; drop table yourTable;
See: http://xkcd.com/327/
I believe you should do this instead:
String query = "select * from TABLE_NAME WHERE column_name=?";
String[] selection = new String[1];
selection[0] = users_entered_value;
Cursor c = db.rawQuery(query, selection);
ETA: Actually, the more I think about it, the more I think you're going in the wrong direction. If your app depends on a database query returning exactly one unique match to an arbitrary string entered by the user, it's probably going to be broken a great deal of the time.
What you should probably do is something like this:
String query = "select * from TABLE_NAME WHERE column_name LIKE ?";
String[] selection = new String[1];
selection[0] = "%" + users_entered_value + "%";
Cursor c = db.rawQuery(query, selection);
and then iterate through the results and pick a "best" match according to your own criteria.
Also, you should create the table with case-insensitive matching for the column(s) you're going to be searching.
SQLiteDatabase db;
db.rawQuery("select * from yourTable where your_column_name = 'users_entered_value' limit 1", null);
SQLiteDatabase db;
// make connection to your database ;
Cursor c = null ;
String SQL = "select * from TABLE_NAME where column_name='VALUE'";
c = db.rawQuery(SQL);
c contains your result array of query you fired.
You can retrieve values using loop.
i am trying to select some accounts depending on the updating time..
My Table named as account and has columns like createdOn , updatedOn, acountName etc.
Now the date is being stored as string 2012-03-20
How can i make sql query to select diff accounts depending on date.
Here is my code
public ArrayList<Account> getAllAccountsForReports(Date dateTo, Date dateFrom)
{
ArrayList<Account> accounts = new ArrayList<Account>();
String queryString = "SELECT * FROM MAAccounts WHERE updatedOn = ? BETWEEN updatedOn = ? ORDER BY accountType, accountName";
Cursor result = mDb.rawQuery(queryString, new String[]{ dateToDB(dateTo), dateToDB(dateFrom)});
Please tell me how can i correct my sql query.
Best Regards
Your BETWEENsyntax is off, what you want is probably;
SELECT * FROM MAAccounts
WHERE updatedOn
BETWEEN ? AND ?
ORDER BY accountType, accountName
Since you're storing by 'yyyy-MM-dd', between should work well using a string.
I wasn't sure what table name to use since you said it was called account in the question and MAAccounts in the code and the columns are mis-spelled in the question, so of course you need to adapt it to your actual column names.
I want to execute a sqlite query:
select * from table_name where id in (23,343,33,55,43);
The values in the in clause need to be taken from an array of strings:
String values[] = {"23","343","33","55","43"}
How can I achieve that?
I believe a simple toString() will mostly do the trick:
String values[] = {"23","343","33","55","43"};
String inClause = values.toString();
//at this point inClause will look like "[23,343,33,55,43]"
//replace the brackets with parentheses
inClause = inClause.replace("[","(");
inClause = inClause.replace("]",")");
//now inClause will look like "(23,343,33,55,43)" so use it to construct your SELECT
String select = "select * from table_name where id in " + inClause;