sqlite database android get all column values into string array - java

I have a sqlite database in android , for example :
Table 1 person:
column 1: id
column 2: name
column 3: friends
Table 2 friends:
column 1: id
column 2: allFriends
the id is the same in both tables, id in table1 == id in table2
i want to get all the values from table2 in specific column "allFriends" by the id and insert all the String values from the column into String array / arrayList.

Try this,
public ArrayList<String> getAllFriends(int id) {
ArrayList<String> friendsNames = new ArrayList<>();
SQLiteDatabase sqLiteDatabase = null;
try {
String query = "select * from person P join friends F on F.id = P.id where P.id = " + id;
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
while (cursor.moveToNext()) {
friendsNames.add(cursor.getString(cursor.getColumnIndex("allFriends")));
}
}catch(Exception ex){
Log.e(TAG,"Erro in geting friends "+ex.toString());
}
return friendsNames;
}

Your SQL query:
SELECT allFriends FROM friends where id == Id_from_person
Id_from_person - id of person who friends you want to recieve from DB.
For executing query read this.

Related

Java JTable data from database

I'm new to java and I need help with displaying a joined table/query in jtable.
First, I have done displaying data from 1 table which is:
Select data from 1 table
insert the result to its entity and insert each one of it to a List
return the list to view and insert row to jtable
I am using a DAO pattern, which has a factory, interface, implement, entity and view.
So what if I select data from other table?
Here is my get method in implement for getting book
public List get(String find) {
try {
ps = db.connect().prepareStatement("SELECT * FROM books WHERE title like ? ");
ps.setString(1, "%" + find + "%");
status = db.execute(ps);
if (status) {
books = db.get_result();
listBooks = new ArrayList<>();
while (books.next()) {
entity_books b = new entity_books();
b.setId(books.getInt(1));
b.setId_category(books.getInt(2));
b.setTitle(books.getString(3));
listBooks.add(b);
}
books.close();
return listBooks;
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return null;
}
and then in my view:
listBooks = booksDAO.get(find.getText());
model = (DefaultTableModel) book_table.getModel();
model.setRowCount(0);
listBooks.forEach((data) -> {
model.addRow(new Object[]{
data.getId(),
data.getId_category(),
data.getTitle(),
});
});
This works fine, but I want the query to join table so I can see the category name instead of just ID category. I can do the query, but how do I apply that to my code?
Here is the query for joined table
select title,category from book b
join category c on c.id = b.id_category
Normally if I select only 1 table, I would insert it to its entity ( book table -> book entity ), so how do I handle this with multiple tables?
I didn't use prepared statement, but this code works on my end.
String sql = "SELECT * FROM customer c JOIN company cmp ON c.company_idcompany = cmp.idcompany";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while (rs.next()) {
//Retrieve this from customer table
int id = rs.getInt("idcustomer");
//Retrieve this from customer table
String username = rs.getString("company_username");
//Display values
System.out.println("ID: " + id);
System.out.println("Username: " + username);
}

Loop MySQL run with java

I have 3 tables having the following content :
Author
idAuthor INT
name VARCHAR
Publication
idPublication INT
Title VARCHAR
Date YEAR
Type VARCHAR
Conference
author_has_publication
author_idAuthor INT
publication_idPublication INT
I am trying to do relational schema on the authors. The objectif is to show the number of publication they have in common. The authors name are parameters, I can have up to 8 names. My code is giving the number of common publication between 2 authors, so i have to loop it. I am currently using a Java loop and SQL statement to do that. Here is the SQL part
private int runQuery(String a1, String a2){ // a1 author 1 and a2 author 2
try {
auth1 = new ArrayList<String>();
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb", "root", "ROOT");
Statement stmt = connection.createStatement();
long start = System.currentTimeMillis();
String queryUpdate1 = "DROP TABLE IF EXISTS temp1;";
String queryUpdate2 = "DROP TABLE IF EXISTS temp2;";
String queryUpdate3 = "CREATE TEMPORARY TABLE IF NOT EXISTS temp1 AS (SELECT Author.name, Publication.idPublication, Publication.title FROM Author INNER JOIN Author_has_Publication ON Author_has_Publication.author_idAuthor=author.idAuthor INNER JOIN Publication ON Author_has_Publication.publication_idPublication=publication.idPublication WHERE Author.name='"+ a1+"');";
String queryUpdate4 = "CREATE TEMPORARY TABLE IF NOT EXISTS temp2 AS (SELECT Author.name, Publication.idPublication, Publication.title FROM Author INNER JOIN Author_has_Publication ON Author_has_Publication.author_idAuthor=author.idAuthor INNER JOIN Publication ON Author_has_Publication.publication_idPublication=publication.idPublication WHERE Author.name='"+ a2+"');";
String query = "SELECT COUNT(*) FROM (SELECT temp1.title from temp1 INNER JOIN temp2 on temp1.idPublication = temp2.idPublication) as t;";
stmt.executeUpdate(queryUpdate1);
stmt.executeUpdate(queryUpdate2);
stmt.executeUpdate(queryUpdate3);
stmt.executeUpdate(queryUpdate4);
ResultSet rs = stmt.executeQuery(query);
int result = -1;
while (rs.next()) {
result = rs.getInt(1);
}
System.out.println("result = " + result);
long end = System.currentTimeMillis() - start;
queryTimeLabel.setText("Query Execution Time :"+end);
connection.close();
return result;
} catch (Exception e) {
System.out.println(e);
}
return -1;
}
Here is the loop part (to repeat the SQL when there are more than 2 authors given) and generate the graph :
public void actionPerformed(ActionEvent e) {
graph = new mxGraph();
Object parent = graph.getDefaultParent();
authVertex = getAuthors();
// ///////////////////////////////////
// CREATES GRAPH, Graph only shows up after you resize the window
graph.getModel().beginUpdate();
try {
int i = 0;
for(String a: authVertex.keySet()){
int j = 0;
for(String b: authVertex.keySet()){
if(j > i) {
graph.insertEdge(parent, null, String.valueOf(runQuery(a,b)), authVertex.get(a), authVertex.get(b)); // loop the SQL statement 2 by 2.
}
j++;
}
i++;
}
} finally {
graph.getModel().endUpdate();
}
graphComponent = new mxGraphComponent(graph);
graphPan.removeAll();
graphPan.add(graphComponent);
setVisible(true);
// /////////////////////////////////////////
}
My code is currently working, but I would like to know if it was possible to increase the performance by passing everything into MySQL, that means that I enter the authors name in parameter and the loop is hangled by MySQL, I check the MySQL procedure but my issue is how to handle the authors names parameter as it is a variable.
One way, in a single statement:
SELECT COUNT(*)
FROM Author_has_Publication AS ap1
JOIN Author_has_Publication AS ap2 ON ap1.publication_idPublication =
ap2.publication_idPublication
JOIN Author AS a1 ON ap1.author_idAuthor = a1.id_Author
JOIN Author AS a2 ON ap2.author_idAuthor = a2.id_Author
WHERE a1.name = '...'
AND a2.name = '...'
Another way may be
SELECT COUNT(*)
FROM
(
SELECT ahp.publication_idPublication, COUNT(*)
FROM Author_has_Publication AS ahp
JOIN Author AS a ON a.id_Author = ahp.author_idAuthor
WHERE a.name IN ('...', '...')
GROUP BY ahp.publication_idPublication
HAVING COUNT(*) = 2 -- Number of authors
) x
Composite indexes needed:
Author_has_Publication: (author_idAuthor, publication_idPublication)
Author_has_Publication: (publication_idPublication, author_idAuthor)
Author: (name, id)
Note: Each technique can be rather easily extended to more than 2 authors. The second query could even be adapted to "at least 3 of these 5 authors": 5 names in IN and HAVING COUNT(*) >= 3.

How to get Data from getAll() method inside an Activity

Database structure:
Detail table
rid name
1 Beta
2 Release
Record table
recid rname conrid (conrid is rid from Detail table)
1 App1 1
2 App2 1
3 App3 2
4 App4 1
I have written a method to get all the data from both the tables (Detail and Record) based on rid and conrid.
Here is the code:
String select = "SELECT rname FROM " + TABLE_RECORD+ " where conrid =" +detail.getId();
It seems you are closed in a loop where you're byting your tail...
So, I'll mix together your code with the answer provided by #MD.
I'm confident he doesn't take it bad. ;)
You will need to add a Class named RecDet (containing the Name field from Detail and RName from Record).
Use that one in place of Detail and Record.
// to get all data from Detail and Record tables
public List<RecDet> getAll()
{
List<RecDet> listRecDet = new ArrayList<RecDet>();
// Select All Query
String selectQuery =
"SELECT Details.name, Record.rname FROM Detail INNER JOIN Record " +
"ON Record.conrid = Detail.rid";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor != null && cursor.moveToFirst())
{
do
{
RecDet recdet = new RecDet();
recdet.setName(cursor.getString(cursor.getColumnIndex("name")));
recdet.setRname(cursor.getString(cursor.getColumnIndex("rname")));
listRecDet.add(recdet);
} while (cursor.moveToNext());
}
return listRecDet;
}
Let's try this
select Details.name,Record.rname from Detail INNER JOIN Record ON Record.conrid=Detail.rid

How to swap values in columns SQLite?

I have table ( id , text) and I need to swap two values in columns like this:
Before.
1 one.
2 two.
3 three.
After ( 1 and 3 swap)
1 three
2 two
3 one
To update each row, you need something like this:
void updateMyTableText (MyTableRow row)
{
ContentValues values = new ContentValues();
values.put ("text", MyTableRow.text);
String where = "id = ?";
String[] whereArgs = new String[1];
whereArgs[0] = Long.toString (row.id);
getDb().update ("MyTable", values, where, whereArgs);
}
where MyTableRow is
class MyTableRow
{
long id;
String text;
}
You'll also need some queries to get the "text" for rows 1 and 3.
Here's one way to do a query:
long getId (String text)
{
// do the query
String query = "select id from MyTable where text = ? ";
String[] args = new String[1];
args[0] = text;
Cursor cursor = getDb().rawQuery (query, args);
if (cursor == null)
throw new IllegalStateException ("cursor is null");
try
{
// get the results
if (!cursor.moveToNext())
return -1; // row not found
long id = cursor.getLong (0);
return id;
}
finally
{
cursor.close();
}
}
Are you trying to change the values in the rows themselves? Most databases systems don't let you arbitrarily swap values since there is an assumption that they are permanently associated. You could issue UPDATE commands to permanently modify the values, but doing this temporarily will probably be an issue handled once the data is returned.
UPDATE table_name
SET text=three
WHERE id=1;
UPDATE table_name
SET text=one
WHERE id=3;
// Assuming id1 < id2
void swap(id1,id2)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues CV = new ContentValues();
// First get the 2 rows
Cursor res = db.rawQuery("SELECT COLUMN_NAME FROM "+ TABLE_NAME +" WHERE ID IN ("+id1+","+id2+") ORDER BY ID ASC",null);
res.moveToFirst();
CV.put("COLUMN_NAME",res.getString(0));
//Update 1st row with 2nd item
db.update(TABLE_NAME,CV,"ID = ?",new String[]{id2+""});
res.moveToNext();
CV.put("COLUMN_NAME",res.getString(0));
//Update 2nd row with 1st item
db.update(TABLE_NAME,CV,"ID = ?",new String[]{id1+""});
}
Hope it helps!!

How to retrieve records from db where a particular column is equal to a set of Strings?

I have a table T1 with columns ID(primary key,varchar), name(varchar), value(number) and key(number).I have a String array which consists of ID's and I want to retrieve all the records with those id in the String array from TABLE T1 in a single query. How can I write this query in oracle?
I'm currently using a for loop and getting the records:
for(String id: idList)
{
//Query to get record one by one (Select * from t1 where ID='id')
}
Could you suggest me a query to retrieve all these values in a single query?
Use the following query
select * from t1 where id in ('id1', 'id2', 'id3')
To get the ArrayList into the format, do the following
StringBuilder sb = New StringBuilder();
for(String id: idList)
{
sb.append("'"+id+"',")
}
sb.deleteCharAt(sb.length() -1);
sb.toString();
//Prep the query string
//---------------------------------
$strQ ="";
$len = count($idList);
$strQ = "'".$idList[0]."'";
for($i=1; $i<$len; $i++){
$strQ += " or ID = '".$idList[$i]."'";
}
//Now Da Query
//---------------------------------------
"Select * from t1 where ID= ".$strQ;
//---------------------
I've explained da above using PHP...
Try this
List<Long> itemIDs = new ArrayList<Long>();
itemIDs.add(10);
....
....
AuthService.deletePracticeAppMenu(itemIDs, selectedPractice.getID());
public void deletePracticeAppMenu(List<Long> prAppMenuIDs, Long practiceID) {
String query = "delete from PracticeAppMenu where PrAppMenuID in (:appMenuIDs) and practiceID = :pracid ";
Query q = getCurrentSession().createQuery(query);
q.setParameterList("appMenuIDs", prAppMenuIDs);
q.setParameter("pracid", practiceID);
q.executeUpdate();
}

Categories

Resources