I have a local SQLite Database in may App. I create and open the Database like this:
CookieClickerBase = getBaseContext().openOrCreateDatabase(CookieBase, MODE_PRIVATE, null);
CookieClickerBase.execSQL("CREATE TABLE IF NOT EXISTS cookiedata(what TEXT, data LONG)");
I insert some thin into the table link this:
CookieClickerBase.execSQL("INSERT INTO cookiedata VALUES ('Image','3')");
But now I wont to change the data from 3 to 9 in the table entry, where what = Image.
How can I do that?
THANKS!
You could use an UPDATE statement with execSQL():
CookieClickerBase.execSQL("UPDATE cookiedata SET data = 9 WHERE what ='Image'");
or use the recommended method which is update() with ContentValues:
ContentValues cv = new ContentValues();
cv.put("data", "9");
int rows = CookieClickerBase.update("cookiedata", cv, "what = ?", new String[] {"Image"});
The variable rows will contain the number of updated rows.
Related
I am working on an android project, basicli I have some x,y coordinates in my sqlite but when I add a new data I want to check the data and if there is same data overwrite it.
public void DBCreate(){
SQLITEDATABASE = openOrCreateDatabase("LatLongDatabase", Context.MODE_PRIVATE, null);
SQLITEDATABASE.execSQL("CREATE TABLE IF NOT EXISTS myTable(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, mCurrentLocationLAT VARCHAR,mCurrentLocationLONG VARCHAR);");
}
public void SubmitData2SQLiteDB(){
SQLiteQuery = "INSERT INTO myTable (mCurrentLocationLAT, mCurrentLocationLONG) VALUES('"+mCurrentLocation.getLatitude()+"','"+mCurrentLocation.getLongitude()+"');";
SQLITEDATABASE.execSQL(SQLiteQuery);
Toast.makeText(CampaignActivity.this,"OK", Toast.LENGTH_LONG).show();
}
You need to use UPDATE query to update the row with PRIMARY_KEY if data exists or INSERT new row.
Since your table have a PRIMARY_KEY as id, you can check if row exists as below.
SELECT EXISTS(SELECT 1 FROM myTable WHERE id='ROW_ID');
If above query returns 1, then data exists, and you need to use UPDATE query as below, else use INSERT query.
UPDATE myTable SET mCurrentLocationLAT=value1, mCurrentLocationLONG=value2 WHERE id='ROW_ID';
SQLite has an INSERT OR REPLACE statement which can be shortened just to REPLACE which will insert a new row if it doesn't exist, or replace (delete then insert) a row if it does exist. Read the docs to learn about primary key constraints and how to handle them.
REPLACE INTO positions (title, min_salary)
VALUES
('Full Stack Developer', 140000);
How do I display exactly one data (specified row and column value ) from SQLite database to a paragraph in iText pdf? I used iText pdf and extracted the table from database but I cannot extract a specific data from it and add it to paragraph.
I am making a CV maker app and I need to display the user data from database to pdf using Android.
Pick whatever is the unique column on the database(maybe a username) and use it to query the database for specific rows that contain the username, since it's a profile table is safe to assume that the user's profile will prop up just once.
Then you can get out specific columns from the returned cursor.
SQLiteDatabase db = this.getWriteableDatabase();
String query = "SELECT * FROM " + your_table_name + " WHERE " + username_column + " = ?";
Cursor cursor = db.rawQuery(query, new String[] {thUsersUsername});
If (cursor.getCount == 1){
cursor.moveToFirst();
//get a specific column eg address
String address = cursor.getString(cursor.getColumnIndex(enterColumNameHere));
Toast.makeText(this, address, Toast.LENGTH_LONG).show;
cursor.close();
db.close();
}
That's basically what you need.
I have a simple app that contains an Sqlite database containing 2 tables:
TABLE_CHAP that contains:
_id
Chapter_title
Number_of_flashcards
TABLE_Flash contains:
_id
Chap_id
flashcard content
I upload the content of the database to the assets folder, TABLE_FLASH contains a number of flashcards that belongs to each chapter.
What I'm trying to do is to count the frequency of Chap_id in TABLE_FLASH and insert this number to Number_of_flashcards in TABLE_CHAP and afterward display the number_of_flashcard in front of the concerned Chapter_Title.
the Number_of_flashcards is dynamic as the user may add his own flashcards to each chapter.
public void nberOfFlahcards(){
int xy= getChap_tableCount();
ContentValues contentValues = new ContentValues();
database = openHelper.getWritableDatabase();
for(int i=1; i<=xy; i++){
String countQuery = "SELECT * FROM TABLE_CHAP WHERE Chap_ID = " + i;
Cursor cursor = database.rawQuery(countQuery, null);
int total_count=cursor.getCount();
Log.v(TAG, "Nber of Flashcards for chapter"+i+"is: "+total_count);
contentValues.put(KEY_NBER_FLAHCARDS, Integer.toString(total_count));
database.update(TABLE_CHAP,contentValues, KEY_NBER_FLAHCARDS,null );
this code gave me always 0, please check where's the error and if you have better code or better architecture for the database please advise.
This update can be done with a single query
UPDATE TABLE_CHAP SET Number_of_flashcards =
(SELECT count(*)
FROM TABLE_Flash AS tf
WHERE tf.Chap_id=TABLE_CHAP._id)
But I'd better have a method int getNumberOfFlashcards(int chap_id) which computes the count for the given chap_id.
I have a problem with to update a varchar in the sqlite database in java.
when I run this source, than I get a error.
I want String a to update to String b.
This is my source:
public void onClick (View v){
String a = "Test1";
String b = "Test2";
db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
ContentValues values = new ContentValues();
values.put("Level1", b);
db.update("Game", values, a, null);
db.close();
}
And this is my Error:
Error updating Level1=Test2 using update Game SET Level1=? WHERE Test1.
can someone help me?
Thanks!
I'm not 100% sure what you are trying to achieve, however, you added a as a where clause and did not provide any arguments, so consequently you got the SQL statement shown in the error.
From the API:
public int update (String table, ContentValues values,
String whereClause, String[] whereArgs)
This one works ...
db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
ContentValues values = new ContentValues();
values.put("Level1", b);
db.update("Game", values, "Level1=?", new String[] {a} );
db.close();
... if this is the resulting SQL you want to execute:
update Game SET Level1=? WHERE Level1 = 'Test1'
update Game SET Level1=? WHERE Test1.
Where Test1 is.. what? Where is the conditional part of your update statement. It's expecting something like:
update Game SET Level1=? WHERE ColumnName='Test1'
Taken from this website:
If the UPDATE statement does not have a WHERE clause, all rows in the table are modified by the UPDATE. Otherwise, the UPDATE affects only those rows for which the result of evaluating the WHERE clause expression as a boolean expression is true.
A String on it's own is in no way a boolean expression.
I have an Android SQLite Database and I inserted some rows. After I deleted these rows the ID column continues from the last ID and I would like to restart the counting from 1.
Inside your .db file there's an table called sqlite_sequence
Each row has two columns 'name' which is the name of the table 'seq' a integer indicating the current last value at this table
You can update it to 0
But beware if your table use this id as the unique identifier.
Take a look at this answer: SQLite Reset Primary Key Field
Try:
delete from sqlite_sequence where name='your_table';
If you want to reset every RowId via content provider try this
rowCounter=1;do {
rowId = cursor.getInt(0);
ContentValues values;
values = new ContentValues();
values.put(Table_Health.COLUMN_ID,
rowCounter);
updateData2DB(context, values, rowId);
rowCounter++;
while (cursor.moveToNext());
public static void updateData2DB(Context context, ContentValues values, int rowId) {
Uri uri;
uri = Uri.parseContentProvider.CONTENT_URI_HEALTH + "/" + rowId);
context.getContentResolver().update(uri, values, null, null);
}