How do you check to see if a Record (ContentValues) already exists in the Database?
public void insertData(String ActId,String Dstcode,String Mandicode,String Traderlicno,String licenseId,String licensename,String Gatepassno,String FarmerId,String Farmername,String FarmerFatherName,String CommodityGrpCode,String CommodityCode,String VartyCode,String Cwght,String UntCode,String FnlPrice,String lgndate,String Ip,String dte,String IEMIN0,String ModelNo,String BoardName,String BrandName,String SIMNo)
{
ContentValues cv = new ContentValues();
cv.put(DatabaseHandler.AUCTIONINFO_ActId, ActId);
cv.put(DatabaseHandler.AUCTIONINFO_Dstcode, Dstcode);
cv.put(DatabaseHandler.AUCTIONINFO_Mandicode, Mandicode);
cv.put(DatabaseHandler.AUCTIONINFO_Traderlicno, Traderlicno);
cv.put(DatabaseHandler.AUCTIONINFO_licenseId, licenseId);
cv.put(DatabaseHandler.AUCTIONINFO_licensename, licensename);
cv.put(DatabaseHandler.AUCTIONINFO_Gatepassno, Gatepassno);
cv.put(DatabaseHandler.AUCTIONINFO_FarmerId, FarmerId);
cv.put(DatabaseHandler.AUCTIONINFO_Farmername, Farmername);
cv.put(DatabaseHandler.AUCTIONINFO_FarmerFatherName, FarmerFatherName);
cv.put(DatabaseHandler.AUCTIONINFO_CommodityGrpCode, CommodityGrpCode);
cv.put(DatabaseHandler.AUCTIONINFO_CommodityCode, CommodityCode);
cv.put(DatabaseHandler.AUCTIONINFO_VartyCode, VartyCode);
cv.put(DatabaseHandler.AUCTIONINFO_Cwght, Cwght);
cv.put(DatabaseHandler.AUCTIONINFO_UntCode, UntCode);
cv.put(DatabaseHandler.AUCTIONINFO_FnlPrice, FnlPrice);
cv.put(DatabaseHandler.AUCTIONINFO_lgndate, lgndate);
cv.put(DatabaseHandler.AUCTIONINFO_Ip, Ip);
cv.put(DatabaseHandler.AUCTIONINFO_dte, dte);
cv.put(DatabaseHandler.AUCTIONINFO_IEMIN0, IEMIN0);
cv.put(DatabaseHandler.AUCTIONINFO_ModelNo, ModelNo);
cv.put(DatabaseHandler.AUCTIONINFO_BoardName, BoardName);
cv.put(DatabaseHandler.AUCTIONINFO_BrandName, BrandName);
cv.put(DatabaseHandler.AUCTIONINFO_SIMNo, SIMNo);
database.insert(DatabaseHandler.TABLE_AUCTIONINFO, null, cv);
}
Edit:
myDB= openOrCreateDatabase("DBName", MODE_PRIVATE, null);
myDB.execSQL("CREATE TABLE IF NOT EXISTS MyTable (your query goes here);");
Cursor cursor = myDB.rawQuery("select AUCTIONINFO_ActId from TABLE_AUCTIONINFO where AUCTIONINFO_licenseId = licenseId;", null);
if(cursor.getCount()!=0)
{
// now you can insert the record
}
else
{
}
Related
This is my database
public void DBCreate() {
SQLITEDATABASE = getActivity().openOrCreateDatabase("FavoritesDB", Context.MODE_PRIVATE, null);
SQLITEDATABASE.execSQL("CREATE TABLE IF NOT EXISTS favorite(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, word VARCHAR, meaning VARCHAR);");
}
This is how I am creating new rows:
String query = "INSERT INTO favorite (word,meaning) VALUES('"+wordd+"', '"+mean+"');";
Cursor c=SQLITEDATABASE.rawQuery("SELECT * FROM favorite WHERE id=?", null);
if (c.moveToFirst())
{
Toast.makeText(getActivity(),"inserted",Toast.LENGTH_LONG).show();
SQLITEDATABASE.execSQL(query);
}
else
{
Toast.makeText(getActivity(),"exists",Toast.LENGTH_LONG).show();
}
How to check data before inserting value into table?
before inserting perform select query and check the cursor size if it is >0 than record already exist .
I am not sure why are you passing null in your query
Cursor c=SQLITEDATABASE.rawQuery("SELECT * FROM favorite WHERE id=?", null);
instead
Cursor c=SQLITEDATABASE.rawQuery("SELECT * FROM favorite WHERE id=?", new String[]{"your id1"});
or
if you want to select all record then
Cursor c=SQLITEDATABASE.rawQuery("SELECT * FROM favorite");
try this code:
Cursor c = SQLITEDATABASE.rawQuery("SELECT * FROM favorite WHERE id=?", new String[]{"your_id_name"});
Log("Cursor Count : " + c.getCount());
if(c.getCount()>0)
{
Toast.makeText(getActivity(),"exists",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getActivity(),"inserted",Toast.LENGTH_LONG).show();
SQLITEDATABASE.execSQL(query);
}
And your select query should look like:
String sql ="SELECT PID FROM "+TableName+" WHERE PID="+pidValue;
Options:
If you do not want to repeat any of the values in a column, set the column setting in the CREATE method to "UNIQUE" or even "PRIMARY KEY" if the content should be the primary key to recognize. Thus you can probably avoid any repetitions without having to check.
Loop through the table:
Cursor c = SQLITEDATABASE.rawQuery("SELECT * FROM favorite", null);
if (c.getCount() > 0) {
String searchString = "some word"; // word you are about to insert
while (c.moveToNext()) {
c.moveToFirst();
int colIndex = c.getColumnIndex("word");
String wordInCurrentRow = c.getString(colIndex);
if (!(wordInCurrentRow.equals(searchString))) {
// insert method
} else {
// do nothing
Log.d("word already existing", "nothing to insert");
}
}
}
I'm fetching data from server and storing it in local db i.e sqlite. It is inserting duplicate values in sqlite.
So my condition is :
Check with sqlite db is empty,insert the record
Check the id column of sqlite already present, if yes update it or else insert.
I've done so for :-
SQLiteDatabase db = dbhelp.getWritableDatabase();
ContentValues values = new ContentValues();
String sqlq = "Select clid from client_detail";
Cursor cccs = db.rawQuery(sqlq, null);
if (cccs.getCount()== 0) {
values.put("clid", queryValues.get("clid"));
values.put("_id", queryValues.get("_id"));
values.put("client_id", queryValues.get("client_id"));
values.put("client_name", queryValues.get("client_name"));
values.put("client_mobile", queryValues.get("client_mobile"));
values.put("client_phone", queryValues.get("client_phone"));
values.put("client_email", queryValues.get("client_email"));
values.put("client_address", queryValues.get("client_address"));
db.insert("client_detail", null, values);
}else{
if (cccs.moveToFirst()) {
do{
Log.d("Client ID",""+cccs.getString(0));
clid.add(cccs.getString(0));
String temp = cccs.getString(0);
Log.d("Clid",temp);
if(temp.equals(queryValues.get("clid"))) //checking each id present in db
{
values.put("clid", queryValues.get("clid"));
values.put("lawyer_id", queryValues.get("_id"));
values.put("client_id", queryValues.get("client_id"));
values.put("client_name", queryValues.get("client_name"));
values.put("client_mobile", queryValues.get("client_mobile"));
values.put("client_phone", queryValues.get("client_phone"));
values.put("client_email", queryValues.get("client_email"));
values.put("client_address", queryValues.get("client_address"));
db.update("client_detail", values, null, null);
}
else{
values.put("clid", queryValues.get("clid"));
values.put("lawyer_id", queryValues.get("_id"));
values.put("client_id", queryValues.get("client_id"));
values.put("client_name", queryValues.get("client_name"));
values.put("client_mobile", queryValues.get("client_mobile"));
values.put("client_phone", queryValues.get("client_phone"));
values.put("client_email", queryValues.get("client_email"));
values.put("client_address", queryValues.get("client_address"));
db.insert("client_detail", null, values);
}
}while(cccs.moveToNext());
}
}
Im using the following code to add values to db.
public void addComplianceAcceptability(ComplianceAcceptability complianceAcceptability) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_ID, complianceAcceptability.getId());
contentValues.put(KEY_COUNTRY_ID, complianceAcceptability.getCountryId());
contentValues.put(KEY_DOMAIN_ID, complianceAcceptability.getDomainId());
contentValues.put(KEY_UNIT_ID, complianceAcceptability.getUnitId());
contentValues.put(KEY_COMPLIANCE_ID, complianceAcceptability.getComplianceId());
contentValues.put(KEY_COMPLIANCE_NAME, complianceAcceptability.getCompliancenName());
contentValues.put(KEY_COMPLIANCE_FREQUENCY, complianceAcceptability.getComplianceFrequency());
contentValues.put(KEY_COMPLIANCE_APPLICABLE, complianceAcceptability.getComplianceApplicable());
contentValues.put(KEY_COMPLIANCE_OPTED, complianceAcceptability.getComplianceOpted());
sqLiteDatabase.insert(TABLE_COMPLIANCE_ACCEPTABILITY, null, contentValues);
sqLiteDatabase.close();
}
Imm trying to access the values using the following code,
public List<ComplianceAcceptability> getAllAcceptability() {
List<ComplianceAcceptability> complianceAcceptabilityList = new ArrayList<>();
String selectQuery = "SELECT * FROM " + TABLE_COMPLIANCE_ACCEPTABILITY;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
ComplianceAcceptability complianceAcceptability = new ComplianceAcceptability();
complianceAcceptability.setId(Integer.parseInt(cursor.getString(0)));
complianceAcceptability.setCountryId(cursor.getString(1));
complianceAcceptability.setDomainId(cursor.getString(2));
complianceAcceptability.setUnitId(cursor.getString(3));
complianceAcceptability.setComplianceId(cursor.getString(4));
complianceAcceptability.setCompliancenName(cursor.getString(5));
complianceAcceptability.setComplianceFrequency(cursor.getString(6));
complianceAcceptability.setComplianceApplicable(cursor.getString(7));
complianceAcceptability.setComplianceOpted(cursor.getString(8));
} while (cursor.moveToNext());
}
return complianceAcceptabilityList;
}
The problem is that it returns an empty array. But when I try to print the contentValues within addComplianceStatus, it of course prints the array of all values.
You never add anything to complianceAcceptabilityList. You just assign it once, then do nothing to it before returning it. Maybe you want to add complianceAcceptability into it at each iteration through the cursor?
Here you are not adding the complianceAcceptability object to the complianceAcceptabilityList, your modified code:
if (cursor.moveToFirst()) {
do {
ComplianceAcceptability complianceAcceptability = new ComplianceAcceptability();
complianceAcceptability.setId(Integer.parseInt(cursor.getString(0)));
complianceAcceptability.setCountryId(cursor.getString(1));
complianceAcceptability.setDomainId(cursor.getString(2));
complianceAcceptability.setUnitId(cursor.getString(3));
complianceAcceptability.setComplianceId(cursor.getString(4));
complianceAcceptability.setCompliancenName(cursor.getString(5));
complianceAcceptability.setComplianceFrequency(cursor.getString(6));
complianceAcceptability.setComplianceApplicable(cursor.getString(7));
complianceAcceptability.setComplianceOpted(cursor.getString(8));
complianceAcceptabilityList.add(complianceAcceptability);
} while (cursor.moveToNext());
}
I'm having some trouble saving a string with an accent to my database and retrieving it.
This is my function that saves a new location to the database. It gets 'myId' and 'location' and inserts them. The println there shows the item as I expect, with the accent. The example I'm using is Mazzarrà.
public long createLocationRecord(String location, int myId) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_OWMID, myId);
values.put(KEY_NAME, location);
System.out.println("newItem in DB = "+location);
long callSQL = db.insertWithOnConflict(TABLE_LOCATION, null, values, SQLiteDatabase.CONFLICT_IGNORE);
if(callSQL==-1)
db.update(TABLE_LOCATION, values, KEY_OWMID + '=' + owmId, null);
return callSQL;
}
This is my function to retrieve all location items. The println here prints out Mezzarra, without the accented à. Am I missing something? Do I need to make a change to my database? It's just a regular Android SQLite DB that I'm opening via SQLiteBrowser.
public ArrayList<String> getLocationList() {
ArrayList<String> list = new ArrayList<String>();
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = "SELECT * "
+ "FROM " + TABLE_LOCATION
+ " ORDER BY _id ASC";
Cursor c = db.rawQuery(selectQuery, null);
if (c != null)
c.moveToFirst();
if (c.moveToFirst()) {
do {
System.out.println("newItem GETTING FROM DB = "+c.getString(c.getColumnIndex(KEY_NAME)));
list.add(c.getString(c.getColumnIndex(KEY_NAME)));
} while (c.moveToNext());
}
c.close();
return list;
}
Thanks for any help anyone can provide.
I am trying to get the last inserted rowid from a sqlite database in Android. I have read a lot of posts about it, but can't get one to work.
This is my method:
public Cursor getLastId() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_WID}, KEY_WID + "=" + MAX(_id), null, null, null, null, null);}
I have tried with MAX, but I must be using it wrong. Is there another way?
Well actually the SQLiteDatabase class has its own insert method which returns the id of the newly created row. I think this is the best way to get the new ID.
You can check its documentation here.
I hope this helps.
Use
SELECT last_insert_rowid();
to get the last inserted rowid.
If you are using AUTOINCREMENT keyword then
SELECT * from SQLITE_SEQUENCE;
will tell you the values for every table.
To get the last row from the table..
Cursor cursor = theDatabase.query(DATABASE_TABLE, columns,null, null, null, null, null);
cursor.moveToLast();
Use moveToLast() in Cursor interface.
From android.googlesource.com
/**
* Move the cursor to the last row.
*
* <p>This method will return false if the cursor is empty.
*
* #return whether the move succeeded.
*/
boolean moveToLast();
Simple example:
final static String TABLE_NAME = "table_name";
String name;
int id;
//....
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
if(cursor.moveToLast()){
//name = cursor.getString(column_index);//to get other values
id = cursor.getInt(0);//to get id, 0 is the column index
}
Or you can get the last row when insertion(Which is #GorgiRankovski have mentioned):
long row = 0;//to get last row
//.....
SQLiteDatabase db= this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_NAME, name);
row = db.insert(TABLE_NAME, null, contentValues);
//insert() returns the row ID of the newly inserted row, or -1 if an error occurred
Also their is a multiple ways you can do this using query:
One is expressed by #DiegoTorresMilano
SELECT MAX(id) FROM table_name. or to get all columns values SELECT * FROM table_name WHERE id = (SELECT MAX(id) FROM table_name).
If your PRiMARY KEY have sat to AUTOINCREMENT, you can SELECT vaules occording to max to min and limit the rows to 1 using SELECT id FROM table ORDER BY column DESC LIMIT 1
(If you want each and every value, use * instead of id)
If you want the last_insert_id just afert a insert you can use that :
public long insert(String table, String[] fields, String[] vals )
{
String nullColumnHack = null;
ContentValues values = new ContentValues();
for (int i = 0; i < fields.length; i++)
{
values.put(fields[i], vals[i]);
}
return myDataBase.insert(table, nullColumnHack, values);
}
The insert method returns the id of row just inserted or -1 if there was an error during insertion.
long id = db.insert("your insertion statement");
db is an instance of your SQLiteDatabase.
Try this:
public Cursor getLastId() {
return mDb.query(DATABASE_TABLE, new String[] { **MAX(id)** }, null, null, null, null, null, null);}
/**
* #return
*/
public long getLastInsertId() {
long index = 0;
SQLiteDatabase sdb = getReadableDatabase();
Cursor cursor = sdb.query(
"sqlite_sequence",
new String[]{"seq"},
"name = ?",
new String[]{TABLENAME},
null,
null,
null,
null
);
if (cursor.moveToFirst()) {
index = cursor.getLong(cursor.getColumnIndex("seq"));
}
cursor.close();
return index;
}
I use this
public int lastId(){
SQLiteDatabase db =
this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from resep", null );
res.moveToLast();
return res.getInt(0);
}
In your DbHelper class,
public long getLastIdFromMyTable()
{
SQLiteDatabase db = this.getReadableDatabase();
SQLiteStatement st = db.compileStatement("SELECT last_insert_rowid() from " + MY_TABLE);
return st.simpleQueryForLong();
}