Insert values into SQLite Database - android

Is there an easier way I can insert data in a table in SQLite? What I need is to insert State_ID and State_Name in Table tblState. Since there are a lot of State in US, is there another way I can use instead of this:
String ROW1 = "INSERT INTO tblState VALUES (1,'Alabama')";
String ROW2 = "INSERT INTO tblState VALUES (2,'Alaska')";
String ROW3 = "INSERT INTO tblState VALUES (3,'California')";
db.execSQL(ROW1);
db.execSQL(ROW2);
db.execSQL(ROW3);
Thanks!

Try for this..
String state[] = { "state1" , "state2",.............};
int id=1;
for(int i=0;i<state.length;i++)
{
db.execSQL("INSERT INTO tblState VALUES (id,state[i])");
id++;
}

You can do the following:
String ALLROWS = "INSERT INTO tblState"
+ "SELECT 1 AS 'State_ID', 'Alabama' AS 'State_Name'"
+ "UNION SELECT 2 AS 'State_ID', 'Alaska' AS 'State_Name'"
+ "UNION SELECT 3 AS 'State_ID', 'California' AS 'State_Name'";
db.execSQL(ALLROWS);

You should use ContentValues for each of the rows you want to insert:
ContentValues values = new ContentValues();
values.put('State_ID', 1);
values.put('State_Name', "Alabama");
and then use db.insert("tblState", null, values) to insert the row. You can write a method to construct your ContentValues:
public ContentValues method(int id, String name) {
ContentValues values = new ContentValues();
values.put('State_ID', id);
values.put('State_Name', name);
}
Your code will be:
db.insert("tblState", null, method(1, "Alabama"));
db.insert("tblState", null, method(2, "Alaska"));
db.insert("tblState", null, method(3, "California"));
Or just loop through all the states...

Related

update column with different values sqlite database android studio

I have a hidden database with 7 columns, one of which is a price and whose values ​​are null. I want to enter some value in the field column for id = 1, then for id = 2 I enter another value etc. and when I fill in the price column I want to update the whole. Is that possible?
My code updates only one value
public boolean updateData(String id,String name, String number_phone, String about, Integer price, String color){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1, id);
contentValues.put(COL_2, name);
contentValues.put(COL_3, number_phone);
contentValues.put(COL_4, about);
contentValues.put(COL_5, price);
contentValues.put(COL_6, color);
db.update(TABLE_NAME, contentValues, " ID = ?" , new String[]{id});
return true;
}
I don't quite get your question but from what i understand this could might help you out.
If you want only one field values to be updated then you need to use for loop.
In onCreate method call this with the array of prices that you want to be updated in table's each row.
Array of prices should not be greater than no. of rows exist in table.
for(int i=0;i<(no. of rows in table);i++){
updateData(rowId,priceArray[i]);
}
Now the update method will be like.
public boolean updateData(String id, Integer price){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_5, price);
db.update(TABLE_NAME, contentValues, " ID = ?" , new String[]{id});
return true;
}
If you want to update certain rows for example {1,4,5} then you have to update it one by one by calling updateData method with id and prices .
But if you want same value of price field to be updated in certain rows like above {1,4,5} than you can
public boolean updateData(Integer price){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_5, price);
db.update(TABLE_NAME, contentValues, " ID = ?" , new String[]{1,4,5});
return true;
}

Update values of a specific column of a specific row. Android SQLite

I have a recyclerview cardholder that inflates using the values of 'NAME' from the table 'ORDERTABLE'. The cardholder also have an EditText which displays the values of column 'QUANTITY' in my SQLite database.
I also have a button to update the database for every changes in EditText.
I have this table ORDERTABLE
id NAME QUANTITY
1 Order1 1
2 Order2 1
3 Order3 1
4 Order4 1
Being more specific, how can i update the QUANTITY of Order2 on onButtonPressed with the new values of my EditText.
EDIT...
I have tried this code but nothing happened
Button to update values
public void addButtonClick(TextView tv_cardrowName_atc, TextView tv_currentPrice_atc, EditText et_quantity_atc, int position) {
int thisQuantity = Integer.parseInt(et_quantity_atc.getText().toString());
thisQuantity++;
String orderName = tv_cardrowName_atc.getText().toString();
String oldQuantity = et_quantity_atc.getText().toString();
String newQuantity = String.valueOf(thisQuantity);
sqliteCBLCAdapter.selectUpdateItem(orderName, oldQuantity, newQuantity);
et_quantity_atc.setText(String.valueOf(thisQuantity));
}
Update Method
public String selectUpdateItem(String orderName, String oldQuantity, String newQuantity) {
SQLiteDatabase sqLiteDatabase = sqLiteCBLC.getWritableDatabase();
String[] columns = {SQLiteCBLC.COL_ORDNAME, SQLiteCBLC.COL_QUANTITY};
Cursor cursor = sqLiteDatabase.query(SQLiteCBLC.TABLE_NAME, columns, SQLiteCBLC.COL_ORDNAME + " = '" + orderName + "'", null, null, null, null);
StringBuffer stringBuffer = new StringBuffer();
while (cursor.moveToNext()) {
int index1 = cursor.getColumnIndex(SQLiteCBLC.COL_ORDNAME);
int index2 = cursor.getColumnIndex(SQLiteCBLC.COL_QUANTITY);
String order = cursor.getString(index1);
String quantity = cursor.getString(index2);
ContentValues contentValues = new ContentValues();
contentValues.put(SQLiteCBLC.COL_QUANTITY, newQuantity);
String[] whereArgs = {quantity};
sqLiteDatabase.update(SQLiteCBLC.TABLE_NAME, contentValues, SQLiteCBLC.COL_QUANTITY + " =? ", whereArgs);
stringBuffer.append(order);
}
return stringBuffer.toString();
}
The easiest way for you to achieve this would be to use a SQL update query as follows:
From the SQLite Web Site:
The SQLite UPDATE Query is used to modify the existing records in a table. You can use a WHERE clause with UPDATE query to update selected rows, otherwise all the rows would be updated.
The syntax for the update query is as follows:
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
So in your case your sql update query would look some thing like this:
UPDATE ORDERTABLE SET QUANTITY = (INSERT VALUE OF YOUR EDIT TEXT) WHERE NAME = 'Order2'
You can then execute your query by using the execSQL() method of your SQLiteDatabase object that you have and passing in the sql query above as the string parameter.
You can try like this below code, In your case you while updating you are updating based on quantity, multiple order will have the same quantity. just check the order name and update it.
public void selectUpdateItem(String orderName, String oldQuantity, String newQuantity) {
if (TextUtils.isEmpty(order)) {
return;
}
ContentValues contentValues = new ContentValues();
final String whereClause = SQLiteCBLC.COL_ORDNAME + " =?";
final String[] whereArgs = {
orderName
};
// if you want to update with respect of quantity too. try this where and whereArgs below
//final String whereClause = SQLiteCBLC.COL_ORDNAME + " =? AND " + SQLiteCBLC.COL_QUANTITY + " =?";
//final String[] whereArgs = {
//orderName, String.valueOf(oldQuantity)
//};
contentValues.put(SQLiteCBLC.COL_QUANTITY, newQuantity);
SQLiteDatabase sqLiteDatabase = sqLiteCBLC.getWritableDatabase();
sqLiteDatabase.update(SQLiteCBLC.TABLE_NAME, contentValues,
whereClause, whereArgs);
}

Android - SQLite Update Statement

I am playing with an example of SQLite I found on the internet. I have an update statement like this:
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?" +
contact.getID(), null);
}
And an update statement like this:
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[]{String.valueOf(contact.getID())});
}
Can someone tell me the difference?
Here is the method signature for an update operation on SQLite database.
int android.database.sqlite.SQLiteDatabase.update(
String table, ContentValues values, String whereClause, String[] whereArgs)
From developer.android.com
You may include ?s in the where clause, which will be replaced
by the values from whereArgs. The values will be bound as Strings.
Btw your first example wouldn't work cause you have included
"KEY_ID + " = ?" + contact.getID()" in whereClause param and kept the whereArgs null. The ?s would'nt be replaced by your arg contact.getId()
Change whereClause in 1st example to this: KEY_ID + " = " + contact.getID()
On your 1st example.The code can't update anything.
The update method whereCause params will be convert to some SQL on where case ,It will replace the ? placeholder with whereArgs.
Such as:
In your 1st example.If contact.getId() return 1,The final SQL is like:
update contact set KEY_NAME = 'your contact name ' where KEY_ID = ? 1
but 2st example final SQL is like:
update contact set KEY_NAME = 'your contact name ' where KEY_ID = 1
So,the first example is not work.

Updating a data base with a single field

I'm currently developing an Android app. The database has 1 column only named content. Here it is the code:
public long insert(String content){
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_CONTENT, content);
return sqLiteDatabase.insert(MYDATABASE_TABLE, null, contentValues);
}
How to make an update for a specific column (according to its index) in that database?
db.update
(
MYDATABASE_TABLE, contentValues , ID_FIELD_CONST + " = ?",
new String[] { idValue }
);
You can use:
ContentValues cv = new ContentValues();
cv.put(KEY1,value1);
cv.put(KEY2,value2);
//... all the fields you want to update
String where = KEY_CONTENT + " = " + value;
db.update(table_name,cv,where,null);
KEY1,KEY2 ... are the name of the fields you want to update
value1,value2... are the new values of the fields you want to update
the where String is to tell in which row you need to update.

Cannot update last row on SQLite

public public udpateNoteInfo(String text){
ContentValues val = new ContentValues();
val.put(KEY_CONTENT5, text);
sqLiteDatabase.update(MYDATABASE_TABLE, val,"ORDER_BY("+KEY_ID+") DESC LIMIT 0,1", new String[]{text});
}
I try to update the last row of the KEY_CONTENT5 column in my SQLite, but it's error.
I guess its mistake at "ORDER_BY("+KEY_ID+") DESC LIMIT 0,1" but I don't know how to make it correct. Please tell me if you know that. Thank you.
ERROR:
09-05 11:47:54.769 E/Database( 4386): Error updating note=Test using UPDATE PERSONAL_TABLE SET note=? WHERE _id = (SELECT max(_id) FROM PERSONAL_TABLE)
Activity class:
public void updateNote(String txt) {
mySQLiteAdapter = new PersonalSQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
cursor = mySQLiteAdapter.queueAll();
if (cursor != null) {
mySQLiteAdapter.udpateNoteInfo(txt);
}
mySQLiteAdapter.close();
}
SQLiteAdapter class (not activity):
public void udpateNoteInfo(String text) {
ContentValues val = new ContentValues();
val.put(KEY_CONTENT5, text);
sqLiteDatabase.update(MYDATABASE_TABLE, val, KEY_ID + " = (SELECT max("
+ KEY_ID + ") FROM " + MYDATABASE_TABLE + ")",
new String[] { text });
}
You can't put an order by in an update.
You can try something like this:
WHERE id=(SELECT max(id) FROM TABLE) if you want to update the last id, assuming your sequences aren't modified.
public void udpateNoteInfo(String text) {
ContentValues val = new ContentValues();
val.put(KEY_CONTENT5, text);
sqLiteDatabase.update(MYDATABASE_TABLE, val, KEY_ID+" = (SELECT max("+KEY_ID+") FROM "+MYDATABASE_TABLE+")", null);
}
My final answer.
You can query the ID, and then, update this row... if your key_id values are not unique, you'll need to use your primary key column(s) instead of this one...
Cursor cLast = db.query(MYDATABASE_TABLE, [KEY_ID], null, null, null, "ORDER_BY("+KEY_ID+") DESC", "LIMIT 0,1");
if (cLast.moveToFirst()) {
long lastKey = cLast.getLong(0); // if it's not a long, use the appropriate getter
sqLiteDatabase.update(MYDATABASE_TABLE, val, "WHERE KEY_ID=?", lastKey);
}
UPDATE table set col = 1 WHERE id = (SELECT MAX(id) FROM table)

Categories

Resources