I am using below query to insert or replace "number" and "time" in "Contacts" table. Is there any way I can insert or replace multiple record in SQLite for Android?
"Insert or replace into Contacts (_id, number, status) values ((select _id from Contacts where number = '123456'), '123456','sent');"
You can improve speed for Multiple/Batch Database Inserting or Replacing operation using concept of transaction and compileStatement so your query will be compiled only once.
For Example:
db.beginTransaction();
try {
String sql = "Insert or Replace into Items (itemNumber, description,unitOfMeasure, weight) values(?,?,?,?)";
ArrayList<ItemMaster> itemsList = // Retrieve your items list here
for(int i=0;i<itemsList.size();i++)
{
SQLiteStatement insert = db.compileStatement(sql);
insert.bindString(1, item.getItemNumber());
insert.bindString(2, item.getItemDescription1());
insert.bindString(3, item.getSellingUOM());
insert.bindDouble(4, item.getWeight());
insert.execute();
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
Try this code for insert multiple entries
public void insertIntoTable(ArrayList<YourModelClass> alist) {
SQLiteDatabase db = this.getWritableDatabase();
String sql = "insert into tableName (colomname1,colomnname2) values(?,?)";
db.beginTransaction();
SQLiteStatement stmt = db.compileStatement(sql);
for (int i = 0; i < alist.size(); i++) {
stmt.bindString(1, alist.get(i).getMethod1());
stmt.bindString(2, alist.get(i).getMethod2());
stmt.execute();
stmt.clearBindings();
}
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
Also Make a Model class to specify your variable names.
eg:
class ModelClass {
String var1,var2;
public void setVar1(String var1)
{
this.var1=var1;
}
public String getVar1()
{
return var1;
}
public void setVar2(String var2)
{
this.var2=var2;
}
public String getVar2()
{
return var2;
}
}
Not sure I understand the query, but it looks like you can just update instead of insert or replace (the select will return null if number is not found)
Update Contacts set status = 'sent' where number in (...)
Related
i have some data from SoapObject, i want insert to sqlite, for better performance, i use the following code :
public void testInsert(String sql, SoapObject rs, int index) {
try {
sql = "INSERT INTO NSPMasterHarga (KdBarang, Wilayah, HargaJual1, HargaJual2) VALUES (?, ?, ?, ?)";
theDatabase = getWritableDatabase();
theDatabase.beginTransaction();
String drop = "DROP TABLE IF EXISTS NSPMasterHarga";
SQLiteStatement stmtDrop = theDatabase.compileStatement(drop);
stmtDrop.execute();
String create = "CREATE TABLE NSPMasterHarga (KdBarang TEXT PRIMARY KEY, Wilayah TEXT, HargaJual1 TEXT, HargaJual2 TEXT)";
SQLiteStatement stmtCreate = theDatabase.compileStatement(create);
stmtCreate.execute();
SQLiteStatement stmt = theDatabase.compileStatement(sql);
int count = rs.getPropertyCount();
for (int i = 0; i < count; i++) {
SoapObject row = (SoapObject) rs.getProperty(i);
for (int j = 1; j <= index; j++) {
stmt.bindString(j, row.getProperty(j - 1).toString().replace("anyType{}", ""));
}
long entryID = stmt.executeInsert();
stmt.clearBindings();
}
/*for (int i = 0; i < NUMBER_OF_ROWS; i++) {
//generate some values
stmt.bindString(1, randomName);
stmt.bindString(2, randomDescription);
stmt.bindDouble(3, randomPrice);
stmt.bindLong(4, randomNumber);
long entryID = stmt.executeInsert();
stmt.clearBindings();
}*/
theDatabase.setTransactionSuccessful();
theDatabase.endTransaction();
theDatabase.close();
}
catch (Exception ex)
{
String err = ex.getMessage();
}
}
When debug, i've got nothing error, but the data not insert to my sqlite.
Any idea or clue ?
Thanks
for better performance
I'm not so sure which part of the code you are referring to. Opening and closing the database after each interaction is terrible for performance. The SQLiteOpenHelper takes care of all this, so you don't need to do anything manually.
Try the following alternative to insert an entry:
public boolean addEntry(){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("column1", "value1"); // make sure the type corresponds to your sql column type
values.put("column2", "value2");
values.put("column3", "value3");
values.put("column4Int", 1);
long newRowId = db.insert(TABLE_NAME, null, values);
Log.d("DBHelper", "Added row " + newRowId + " to DB.");
return newRowId != -1; // -1 means it failed
}
I'm trying to get the value or data from the array that doesn't exists in the database.
public Cursor checkExistence(){
Cursor c=null;
String[] values={"headache","cold"};
SQLiteDatabase db= getReadableDatabase();
String query="SELECT * FROM "+TABLE_SYMPTOMS+" WHERE "+COLUMN_SYMP+" IN ("+toArrayRep(values)+")";
c=db.rawQuery(query,null);
Log.i("From Cursor","Cursor Count : " + c.getCount());
if(c.getCount()>0){
String val= c.getString()
Log.i("From Cursor","No insertion");
}else{
Log.i("From Cursor","Insertion");
}
db.close();
return c;
}
public static String toArrayRep(String[] in) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < in.length; i++) {
if (i != 0) {
result.append(",");
}
result.append("'" + in[i] + "'");
}
return result.toString();
}
In the String values={"headache","cold"} ,headache exists but cold does not exist in the database. From the code above, the Cursor returns Count=1 which is count>0 hence i can't insert into table.I would like to know how i can independently check whether the individual data exists, and the one which doesn't exist will be inserted into table.So in this case, "Cold" would be able to be inserted into the table.
If you use a single query to check all values, then what you get is a list of existing values, and you still have to search in the original list for any differences.
It is simpler to check each value individually:
String[] values = { "headache", "cold" };
SQLiteDatabase db = getReadableDatabase();
db.beginTransaction();
try {
for (String value : values) {
long count = DatabaseUtils.queryNumEntries(db,
TABLE_SYMPTOMS, COLUMN_SYMP+" = ?", new String[] { value });
if (count == 0) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_SYMP, value);
db.insert(TABLE_SYMPTOMS, null, cv);
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
You need check Cursor.moveToFirst()
True = Have records in cursor.
False = Dont have records.
Example my code:
return database.query( table.getNameTable(),
table.getColumns(),
table.getWhereSelectTableScript(),
null,
table.getGroupBySelectTableScript(),
table.getHavingSelectTableScript(),
table.getOrderBySelectTableScript(),
table.getLimitRecordsSelectTableScript());
See more here !
How do I execute SELECT dateTime FROM TABLE_NAME using greendao.
I am trying to fetch the coulmn datetime from table "TABLE_NAME.
To fetch a single column you need to use a raw query
private static final String SQL_DISTINCT_DATE = "SELECT DISTINCT "+YourDao.Properties.EName.datetime+" FROM "+YourDao.TABLENAME;
public static List<String> listEName(DaoSession session) {
ArrayList<String> result = new ArrayList<String>();
Cursor c = session.getDatabase().rawQuery(SQL_DISTINCT_DATE, null);
try{
if (c.moveToFirst()) {
do {
result.add(c.getString(0));
} while (c.moveToNext());
}
} finally {
c.close();
}
return result;
}
I had created sqlite database,What I want to do is that when user enter value then i want to check that the value is already exist if value already exist then UPDATE otherwise INSERT that value, I had tried is...
public long insertDataCat(String id,String cat)
{
try {
SQLiteDatabase db;
db = this.getWritableDatabase(); // Write Data
ContentValues Val = new ContentValues();
Val.put("IDD", id);
Val.put("Categoryy", cat);
long rows = db.insert(TABLE_CATEGARY_MASTER, null, Val);
db.close();
return rows; // return rows inserted.
} catch (Exception e) {
return -1;
}
}
First you get the cursor count of table if any record found in the table mean it's return the cursor count 1 otherwise return zero.If cursor count one mean you perform UPDATE Operation otherwise Perform Insert Operation.
public long insertDataCat(String id,String cat)
{
try {
SQLiteDatabase db;
db = this.getWritableDatabase(); // Write Data
ContentValues Val = new ContentValues();
Val.put("IDD", id);
Val.put("Categoryy", cat);
String selectQuery = "select * from TABLE_CATEGARY_MASTER";
Cursor cursor = db.rawQuery(selectQuery, null);`
if(cursor.getCount()==1)
{
//execute update query here
long updaterow=db.update(TABLE_CATEGARY_MASTER,val);
return updaterow; // return rows inserted.
}
else
{
//Perform the insert query
long rows = db.insert(TABLE_CATEGARY_MASTER, null, Val);
return rows; // return rows inserted.
}
db.close();
} catch (Exception e) {
return -1;
}
}
Can some one please help me with:
I have DB with 5 tables : DB diagram stat_list table is pre-populated with 5 values (Att, pass, TD, inter, pass). And I want create a table in android that will display sum of all the values from table Stat_list for every player. Thanks a lot!
String sQry = "SELECT * FROM Stat_list;";
SQLiteDatabase db = null;
int count = -1;
Cursor cursor = null;
try {
db = SQLiteOpenHelper.getReadableDatabase();
cursor = db.rawQuery(sQry, null);
if (cursor.moveToFirst()) {
do {
int playerScore = Integer.parseInt(cursor.getString(1)) +
Integer.parseInt(cursor.getString(2)) +
Integer.parseInt(cursor.getString(3)) +
Integer.parseInt(cursor.getString(4))
ContentValues playerScores = new ContentValues();
playerScores.put(THE_NAME_OF_THE_SCORE_COLUMN, playerScore);
try{
db.update(NAME_OF_TABLE_WITH_SUMMED_PLAYER_SCORES,playerScores, "PlayerName = " cursor.getString(1), null);
}catch(SQLiteException e){}
}
while (cursor.moveToNext());
}
}
catch (SQLiteException e) {
Log.d("SQL Error", e.getMessage());
}
finally {
cursor.close();
db.close();
}
The snippet above pulls the information from the db, sums up the scores and inserts it into another table. You'll have to put int he specific values though, such as the correct column and table names.