SQLite Insert Query Multiple Database - android

I wrote the following code to insert some records into table from the table of another database.
But I'm unable to, even after executing a sql statement it shows that there are no records in the table.
public int copy_to_all_source_table(String dbpath,String backpath)
{
SQLiteDatabase db1 = this.getWritableDatabase();
//Opening App database(i.e. dbpath) and attaching it as "OLD"
db1.openDatabase(dbpath, null, SQLiteDatabase.OPEN_READWRITE);
String attach_old="ATTACH '"+ dbpath +"' AS OLD";
db1.execSQL(attach_old);
//Opening New File which is Student.db(i.e. dbpath) and attaching it as "NEW"
db1.openDatabase(backpath, null, SQLiteDatabase.OPEN_READWRITE);
String attach_new="ATTACH '"+ backpath +"' AS NEW";
db1.execSQL(attach_new);
// Getting count of records in table of "NEW"
String new_query =" SELECT * FROM 'NEW'.'"+ TABLE_CONTACTS +"'";
Cursor new_data = db1.rawQuery(new_query, null);
Integer new_count= new_data.getCount();
//INSERTING ALL RECORDS FROM TABLE OF NEW TO TABLE OF OLD
String insert_query ="INSERT INTO 'OLD'.'"+ TABLE_CONTACTS +"' SELECT * FROM 'NEW'.'"+ TABLE_CONTACTS +"'";
Cursor success_insert = db1.rawQuery(insert_query, null);
// Getting count of records in table of "NEW"
String after_insert_old_query =" SELECT * FROM 'OLD'.'"+ TABLE_CONTACTS +"'";
Cursor old_data = db1.rawQuery(after_insert_old_query, null);
Integer old_count= old_data.getCount();
}
RESULT:
new_count = 11
old_count = 0
So, no record has been inserted.

You are using rawQuery() to execute an INSERT command. Which will never work.
Use execSQL(), instead
Moreover, the last comment is misleading, because it says you want the count from the NEW table, but you are counting from the OLD one.
And, please, get rid of the string delimiter characters (').
I.e.:
this
String new_query =" SELECT * FROM 'NEW'.'"+ TABLE_CONTACTS +"'";
should be
String new_query = "SELECT * FROM NEW." + TABLE_CONTACTS;

Related

How to delete the rows from a table where a column contains a specific String?

As my title question, I want to delete some rows of table on SQLite where contains specific string.
Here are my methods I tried but there are no any row is deleted. I checked table of SQLite database by get it out and put in to DB Browser for SQLite which is downloaded from https://sqlitebrowser.org/
public void delete1(String table,String COLUMN,String link) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM "+table+" WHERE "+COLUMN+" LIKE "+link+"%");
}
public void delete2(String table,String name){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(table, "PRODUCTNAME" + "LIKE ?", new String[]{name+"%"}) ;
}
Could you tell me how to do it or how have i to correct code ?
using db.delete(table, "PRODUCTNAME " + "LIKE ?", new String[]{name+"%"}) ; will only delete rows that start with the value in name.
Perhpas you want :-
db.delete(table, "PRODUCTNAME " + "LIKE ?", new String[]{"%"+name+"%"}) ;
Then it would delete rows that contain the value rather than start with the value.
With db.execSQL("DELETE FROM "+table+" WHERE "+COLUMN+" LIKE "+link+"%"); you need to enclose the string in single quotes and assuming that you want to delete a row that contains the value then use :-
db.execSQL("DELETE FROM "+table+" WHERE "+COLUMN+" LIKE '%"+link+"%'");
Using the delete convenience method (the first part) is the better option as it protects against SQL Injection, it properly encloses the value, builds the underlying SQL and also returns the number of affected (deleted) rows.
If you use the following, this will write dome debugging information that may assist in debugging :-
public void delete2(String table,String name){
SQLiteDatabase db = this.getWritableDatabase();
Log.d("DELETEINFO","Attempting to delete rows with \n\t->" + name);
int deletedCount = db.delete(table, "PRODUCTNAME " + "LIKE ?", new String[]{"%"+name+"%"}) >0) ;
Log.d("DELETEINFO","Deleted " + deletedCount + " rows.");
}

SQL query not creating my columns?

I am trying to create a fitness app where the database saves a username and password.
then enters their details that saves to a second table. This is my dbHelper.
The error im getting is that my "Username Column does not exist"
But when i go and look at my tables using db browser for sqlite
it shows my tables created and data in my tables
UPDATE : I created 1 table to store all my data and now its not picking up still im getting "not set" from my display method
updated table
// Register table
public static final String COL_1 = "ID";
public static final String COL_2 = "Username";
public static final String COL_3 = "Password";
public static final String COL_4 = "Weight";
public static final String COL_5 = "Height";
public static final String COL_6 = "TargetWeight";
public static final String COL_7 = "TargetSteps";
display method
public String DisplayData(String username,String column)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM "+ TABLE_NAME +" WHERE Username =?",new String[]{username});
if(cursor.moveToFirst()){
return cursor.getString(cursor.getColumnIndexOrThrow(column));
}else{
return "Not set";
}
}
Usage
public void setData() {
db = new dbHelper(this);
try {
userWeight.setText(db.DisplayData(Username, dbHelper.COL_4));
userHeight.setText(db.DisplayData(Username, dbHelper.COL_5));
userTargetWeight.setText(db.DisplayData(Username, dbHelper.COL_6));
userTargetSteps.setText(db.DisplayData(Username, dbHelper.COL_7));
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
TABLE_NAME1 has no Username column. update your method as follow
public String DisplayData(String username, String column) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM "+ TABLE_NAME +" WHERE " + column + " = ? ", new String[]{username});
if (cursor != null && cursor.moveToFirst()){
return cursor.getString(cursor.getColumnIndexOrThrow(column));
} else {
return "Not set";
}
}
and use it like this
.DisplayData("admin", "Username");
Your issue, assuming that value of the 2nd argument of the Displaydata method is Username is that you are querying TABLE_NAME1 (profile_data) table, which doesn't have a column named Username.
Instead I believe you want to be querying the TABLE_NAME (register_table table) table so change :-
Cursor cursor = db.rawQuery("SELECT * FROM "+ TABLE_NAME1 +" WHERE Username = 'admin' ",null);
to :-
Cursor cursor = db.rawQuery("SELECT * FROM "+ TABLE_NAME +" WHERE Username = 'admin' ",null);
Additional re comment :-
Im not longer getting an error but its still not displaying the
correcting infomation . Im getting "Not set " from my displayData
method. from my if ELSE
Assuming that you have added data and getting the above then it is likely that Username does not equate to a row in the table. Try using the following version of DisplayData to debug :-
// Note changed to use recommended convenience query method
// Note closes cursor thus uses intermediate variable (rv) to allow close
public String DisplayData(String username,String column)
{
String rv = "Not set";
SQLiteDatabase db = this.getReadableDatabase();
//Cursor cursor = db.rawQuery("SELECT * FROM "+ TABLE_NAME +" WHERE Username =?",new String[]{username}); //<<<<< replaced
String whereclause = COL_2 + "=?";
String[] whereargs = new String[]{username};
Cursor cursor = db.query(TABLE_NAME,null,whereclause,whereargs,null,null,null);
//<<<<<<<<<< FOLLOWING CODE ADDED TO LOG DEBUG INFO >>>>>>>>>>
Log.d("DISPLAYDATAINFO","Display was called with Username as:- " +
username +
" for Column:- " +
column +
". The Cursor contains " +
String.valueOf(cursor.getCount()) +
" ."
);
//<<<<<<<<<< END OF ADDED DEBUG CODE >>>>>>>>>>
if(cursor.moveToFirst()){
rv = cursor.getString(cursor.getColumnIndexOrThrow(column));
}
cursor.close(); //<<<< SHOULD ALWAYS CLOSE CURSOR WHEN DONE WITH IT
return rv;
}
This should produce output in the log along the lines of :-
05-18 23:08:25.429 2926-2926/fitness.fitness D/DISPLAYDATAINFO: Display was called with Username as:- Fred for Column:- Weight. The Cursor contains 5 .
Display was called with Username as:- Fred for Column:- Height. The Cursor contains 5 .
Display was called with Username as:- Fred for Column:- TargetWeight. The Cursor contains 5 .
Display was called with Username as:- Fred for Column:- TargetSteps. The Cursor contains 5 .
Note 5 because when testing new data is inserted each run so the above indicates the 5th run.
Or in the case of nothing being found (your current issue) something like :-
05-18 23:11:40.342 2926-2926/fitness.fitness D/DISPLAYDATAINFO: Display was called with Username as:- Tom for Column:- Weight. The Cursor contains 0 .
Display was called with Username as:- Tom for Column:- Height. The Cursor contains 0 .
Display was called with Username as:- Tom for Column:- TargetWeight. The Cursor contains 0 .
Display was called with Username as:- Tom for Column:- TargetSteps. The Cursor contains 0 .
i.e. Cursor contains 0 = no rows exist for the given username (Tom in this case).
Check if the Username is as expected (note case of letters must match, in the above a row for tom exists but not for Tom hence 0 count for the cursor).
Column retrieval appears to be correct, However, still check that the columns in the output are as expected (can't see that they would not be).

Android SQLite sending query as an email

I was wondering if it was possible to send a query via email that is created through my app as a text file, or similar format that can be viewed on a pc. The query i want to send is
public Cursor getExpiryData (){
SQLiteDatabase db = this.getWritableDatabase();
Cursor expiry = db.rawQuery("select * from " + TABLE_NAME + " WHERE " + COL_4 + " BETWEEN datetime('now', 'localtime') AND datetime('now', '+30 days')", null );
return expiry;
}
To retrieve data from cursor, use this piece of code:
if (cursor.moveToFirst()){
do{
String data = cursor.getString(cursor.getColumnIndex("data"));
// do what ever you want here
}while(cursor.moveToNext());
}
cursor.close();
I don't know exactly the name of your columns. You can add your table data in list of object and follow the link to send email tutorial.
Thanks!

SQL Lite DELETE Query not working

SQLite delete query isn't working. Can anyone tell me how to use db.delete(table, whereClause, whereArgs) method in limit query?!
String query = "DELETE From gpsinfo LIMIT 100 ";
Cursor cursor = db.rawQuery(query, null);
Try this...
Delete from table_name where ID IN (Select ID from table_name limit 100 );
Use execSQL() for SQL like this.
rawQuery() doesn't run the SQL until you move the returned cursor.
Also, you cannot use LIMIT like this.
String query = "DELETE FROM " +TABLE_NAME+ " WHERE " + COLUMN_NAME+ " = " + "'"+text+"'" ;
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(query);
db.close();

SQLite rawquery

I am getting an error with a rawquery on Eclipse on a DB in the assets directory. The DB is 'pre-loaded' with tables and data and the SQL string, first comment line, works in SQLite DB browser. When I copy the SQL string to code and modify to remove quotes it errors. The code below is from the 'standard' public class DataBaseHelper extends SQLiteOpenHelper{ .I am new to android/java and would appreciate any assistance or suggestions.
public Cursor getAllSectionDescriptions( String DBtable, String source){
//Works in DB: SELECT "Description" FROM "SectionProps" WHERE Source = "UK"
//String q = "SELECT Description FROM SectionProps WHERE Source = UK " ; <= errors in code
String q = "SELECT Description FROM " + DBtable + " WHERE Source = " + source + " "; //<== errors in code
//06-24 16:53:03.373: ERROR/AndroidRuntime(1000): Caused by: android.database.sqlite.SQLiteException: no such table: SectionProps: , while compiling: SELECT Description FROM SectionProps WHERE Source = UK
Cursor mCursor = myDataBase.rawQuery(q, null);
mCursor.moveToFirst();
return mCursor;
}//end cursor
Looks like you have to put double quotes around your object names. So you'll want to do this:
String q = "SELECT \"Description\" FROM \"" + DBtable + "\" WHERE Source = \"" + source + "\" ";
Note the double quotes preceded by the escape character '\'
To execute queries, there are two methods: Execute db.rawQuery method Execute db.query method To execute a raw query to retrieve all departments:
Cursor getAllDepts()
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor cur=db.rawQuery("SELECT "+colDeptID+" as _id,
"+colDeptName+" from "+deptTable,new String [] {});
return cur;
}
The rawQuery method has two parameters: String query: The select statement String[] selection args: The arguments if a WHERE clause is included in the select statement Notes The result of a query is returned in Cursor object. In a select statement if the primary key column (the id column) of the table has a name other than _id, then you have to use an alias in the form SELECT [Column Name] as _id cause the Cursor object always expects that the primary key column has the name _id or it will throw an exception .

Categories

Resources