i have an issue with both functions
// Insert a new contact in database
public void insertInSignature(String TITLE_SI) {
try {
// Open Android Database
Boolean b = checkIsDataAlreadyInDBorNot("DELIVERY_SLIP",
"TITLE_SI", TITLE_SI);
if(b==false)
{
// cursor is empty
ContentValues initialValues = new ContentValues();
initialValues.put("TITLE_SI", TITLE_SI);
db.insertWithOnConflict("DELIVERY_SLIP", null, initialValues,
SQLiteDatabase.CONFLICT_IGNORE);
}
} catch (SQLException sqle) {
Log.e(TAG, "insertUser Error");
Log.e(TAG, "Exception : " + sqle);
} finally {
// Close Android Database
databaseHelper.close();
}
}
public boolean checkIsDataAlreadyInDBorNot(String TableName,
String dbfield, String fieldValue) {
db = databaseHelper.getWritableDatabase();
String Query = "Select * from " + TableName + " where " + dbfield + "="
+ "`"+ fieldValue+"`";
Cursor cursor = db.rawQuery(Query, null);
if (cursor.getCount() <= 0) {
return false;
}
return true;
}
I have this function , I'm inserting signature when it's not on the database.. But the function boolean return an SQLexception i don't know why i found informations about the form , but not for my problem.
Here my log.
http://hpics.li/0ae4ba2
I just want to know if the row exist on my database
here my table.
http://hpics.li/1fd3d9a
Thanks by advance if you need for informations ask me
In SQL, strings are delimited with single quotes ', not backticks `.
To avoid such formatting problems, and SQL injections, you should use parameters instead:
String query = "SELECT * FROM " + TableName + " WHERE " + dbfield + "= ?";
Cursor cursor = db.rawQuery(query, new String[] { fieldValue });
Instead of doing a query every time you want to insert, why not make the TITLE_SI column UNIQUE with ON CONFLICT IGNORE or ONC CONFLICT REPLACE? Then you don't need to check, you simply insert and let the uniqueness constraint manage this for you.
Related
I am using SQLite Database in Android. I have used rawQuery in SQLite database. My Database method for that is as follows:
public Cursor selectedDate(String from_dt ,String to_dt)
{
try
{
String str_k="select RowId,Bill_Date from SalesMaster Where Bill_Date between '"+
from_dt+ "'and'"+to_dt+ "'";
System.out.println(str_k);
Cursor c1 = sqldb.rawQuery(
"select RowId from SalesMaster Where Bill_Date between '"+
from_dt+ "'and'"+to_dt+ "'", null);
return c1;
}
catch(Exception e)
{
System.out.println("inside database file "+ e);
return null;
}
}
and my .java file is
public void ReportSell(String from_dt,String to_dt)
{
System.out.println("report selling method has been called");
String RowId="";
item db1 = new item(getBaseContext());
db1.openDb();
try
{
final Cursor cursor = db1.selectedDate(from_dt, to_dt);
if(cursor.moveToFirst())
{
do
{
RowId= cursor.getString(cursor.getColumnIndex("RowId")).toString();
System.out.println("inside java Row Id file "+ RowId);
salesid.add(RowId);
ArrayAdapter <String> adapter = new ArrayAdapter <String>(this,
android.R.layout.simple_list_item_1,
salesid);
} while(cursor.moveToNext());
}
else
{
Toast.makeText(getApplicationContext(), "No data found",
Toast.LENGTH_LONG).show();
}
} catch(Exception e)
{
System.out.println("inside java file "+ e);
}
db1.closeDb();
}
The main problem is that it will return RowId from salesMaster table as per from-date and to-date, but actual problem is it will return values but not include last to-date.
For example, if I want to RowId from 25/02/2015 to 28/02/2015
so it will give RowId from 25/02/2015 to 27/02/2015 but not included 28/02/2015.
You have to replace between to
Expression (min <= expr AND expr <= max)
Change you query to
String str_k="SELECT * from TABLE_NAME Where COLUMN_NAME >='"+from_date+ "' AND <= '"+to_date+ "'";
System.out.println(str_k);
I want to update my database table with multiple where conditions. I already did with single where condition
db.update(TABLE_MISSING_ITEMS, values, KEY_AUTHOR + " = ?",
new String[] { String.valueOf(items.getAuthor()) });
Now i want 2 where condition.
P.S :- No raw query
You can separate the different WHERE conditions with ANDlike this:
db.update(TABLE_NAME,
contentValues,
NAME + " = ? AND " + LASTNAME + " = ?",
new String[]{"Manas", "Bajaj"});
The way I solved my need
public boolean checkHususiKayit(String baslik, String tarih) {
boolean varMi = false;
SQLiteDatabase database = dbHelper.getReadableDatabase();
final String kolonlar[] = {DBHelper.COLUMN_H_ID,
DBHelper.COLUMN_H_ID,
DBHelper.COLUMN_H_BASLIK,
DBHelper.COLUMN_H_TARIH,
DBHelper.COLUMN_H_YOK_TUR,
DBHelper.COLUMN_H_AD,
DBHelper.COLUMN_H_WEB_ID,
DBHelper.COLUMN_H_NUMARA,
DBHelper.COLUMN_H_YURD_ID,
DBHelper.COLUMN_H_YETKILI_AD,
DBHelper.COLUMN_H_YETKILI_ID,
DBHelper.COLUMN_H_TEL,
DBHelper.COLUMN_H_EMAIL,
DBHelper.COLUMN_H_ADDRESS,
DBHelper.COLUMN_H_VAR,
DBHelper.COLUMN_H_GOREVLI,
DBHelper.COLUMN_H_YOK,
DBHelper.COLUMN_H_IZINLI,
DBHelper.COLUMN_H_HATIMDE};
String whereClause = DBHelper.COLUMN_H_BASLIK + " = ? AND " + DBHelper.COLUMN_H_TARIH + " = ?"; // HERE ARE OUR CONDITONS STARTS
String[] whereArgs = {baslik, tarih};
Cursor cursor = database.query(DBHelper.TABLE_NAME_HUSUSI, kolonlar, whereClause, whereArgs, null, null, null + " ASC");
while (cursor.moveToNext()) {
varMi = true;
}
database.close();
cursor.close();
return varMi;
}
THIS CAN ALSO BE DONE LIKE THIS
public void UpdateData(int Cid,int flag,String username,String password)
{
SQLiteDatabase database = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("Status",flag);//I am updating flag here
database.update(TABLE_NAME, cv, ""+KEY_UserName+"= '"+ username+"' AND "+KEY_CID+"='"+Cid+"' AND "+KEY_Password+"='"+password+"'" , null);
database.close();
}
Try this simple query
db.update(TABLE_FF_CHECKLIST_DATA,contentValues, "FFCHECKLISTID = ? and TASK_ID_CHK = ?" , new String[] {"EHS" , "CTO914"});
where "EHS" is value in column FFCHECKLISTID and CTO914 is value in TASK_ID_CHK.
I would like to check whether a record exists or not.
Here is what I've tried:
MainActivity.class
public void onTextChanged(CharSequence s, int start, int before, int count) {
System.out.println("Ontext changed " + new String(s.toString()));
strDocumentFrom = s.toString();
if(s.toString().isEmpty()){
} else {
try{
strTransactionDate = dbHelper.getTransactionDateByDocumentNumber(strDocumentFrom);
//strTotalAmount = dbHelper.getTotalAmountByDocumentNumber(strDocumentFrom);
//strVan = dbHelper.getVanByDocumentNumber(strDocumentFrom);
//etTransactionDate.setText(strTransactionDate);
//etTotalAmount.setText(strTotalAmount);
//Log.d("Van", "" + strVan);
//etVan.setText(strVan);
} catch (SQLiteException e) {
e.printStackTrace();
Toast.makeText(ReceivingStocksHeader.this,
"Document number does not exist.", Toast.LENGTH_SHORT).show();
}
}
DBHelper.class
// TODO DISPLAYING RECORDS TO TRANSRCVHEADER
public String getTransactionDateByDocumentNumber(String strDocumentNumber){
String[] columns = new String[]{KEY_TRANSACTIONDATE};
Cursor c = myDataBase.query(TBL_INTRANS,
columns, null,
null, null, null, null, null);
if(c != null){
c.moveToFirst();
String date = c.getString(0);
return date;
} else {
Log.d("Error", "No record exists");
}
return null;
}
But it doesn't get it to the catch block to display the toast.
What am I doing wrong in here?
public static boolean CheckIsDataAlreadyInDBorNot(String TableName,
String dbfield, String fieldValue) {
SQLiteDatabase sqldb = EGLifeStyleApplication.sqLiteDatabase;
String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
Cursor cursor = sqldb.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
return false;
}
cursor.close();
return true;
}
I hope this is useful to you...
This function returns true if record already exists in db. Otherwise returns false.
These are all good answers, however many forget to close the cursor and database. If you don't close the cursor or database you may run in to memory leaks.
Additionally: You can get an error when searching by String that contains non alpha/numeric characters. For example: "1a5f9ea3-ec4b-406b-a567-e6927640db40". Those dashes (-) will cause an unrecognized token error. You can overcome this by putting the string in an array. So make it a habit to query like this:
public boolean hasObject(String id) {
SQLiteDatabase db = getWritableDatabase();
String selectString = "SELECT * FROM " + _TABLE + " WHERE " + _ID + " =?";
// Add the String you are searching by here.
// Put it in an array to avoid an unrecognized token error
Cursor cursor = db.rawQuery(selectString, new String[] {id});
boolean hasObject = false;
if(cursor.moveToFirst()){
hasObject = true;
//region if you had multiple records to check for, use this region.
int count = 0;
while(cursor.moveToNext()){
count++;
}
//here, count is records found
Log.d(TAG, String.format("%d records found", count));
//endregion
}
cursor.close(); // Dont forget to close your cursor
db.close(); //AND your Database!
return hasObject;
}
Raw queries are more vulnerable to SQL Injection. I will suggest using query() method instead.
public boolean Exists(String searchItem) {
String[] columns = { COLUMN_NAME };
String selection = COLUMN_NAME + " =?";
String[] selectionArgs = { searchItem };
String limit = "1";
Cursor cursor = db.query(TABLE_NAME, columns, selection, selectionArgs, null, null, null, limit);
boolean exists = (cursor.getCount() > 0);
cursor.close();
return exists;
}
Source: here
SELECT EXISTS with LIMIT 1 is much faster.
Query Ex: SELECT EXISTS (SELECT * FROM table_name WHERE column='value' LIMIT 1);
Code Ex:
public boolean columnExists(String value) {
String sql = "SELECT EXISTS (SELECT * FROM table_name WHERE column='"+value+"' LIMIT 1)";
Cursor cursor = database.rawQuery(sql, null);
cursor.moveToFirst();
// cursor.getInt(0) is 1 if column with value exists
if (cursor.getInt(0) == 1) {
cursor.close();
return true;
} else {
cursor.close();
return false;
}
}
You can use SELECT EXISTS command and execute it for a cursor using a rawQuery,
from the documentation
The EXISTS operator always evaluates to one of the integer values 0
and 1. If executing the SELECT statement specified as the right-hand
operand of the EXISTS operator would return one or more rows, then the
EXISTS operator evaluates to 1. If executing the SELECT would return
no rows at all, then the EXISTS operator evaluates to 0.
I have tried all methods mentioned in this page, but only below method worked well for me.
Cursor c=db.rawQuery("SELECT * FROM user WHERE idno='"+txtID.getText()+"'", null);
if(c.moveToFirst())
{
showMessage("Error", "Record exist");
}
else
{
// Inserting record
}
One thing the top voted answer did not mention was that you need single quotes, 'like this', around your search value if it is a text value like so:
public boolean checkIfMyTitleExists(String title) {
String Query = "Select * from " + TABLE_NAME + " where " + COL1 + " = " + "'" + title + "'";
Cursor cursor = database.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
return false;
}
cursor.close();
return true;
}
Otherwise, you will get a "SQL(query) error or missing database" error like I did without the single quotes around the title field.
If it is a numeric value, it does not need single quotes.
Refer to this SQL post for more details
SQLiteDatabase sqldb = MyProvider.db;
String Query = "Select * from " + TABLE_NAME ;
Cursor cursor = sqldb.rawQuery(Query, null);
cursor.moveToLast(); //if you not place this cursor.getCount() always give same integer (1) or current position of cursor.
if(cursor.getCount()<=0){
Log.v("tag","if 1 "+cursor.getCount());
return false;
}
Log.v("tag","2 else "+cursor.getCount());
return true;
if you not use cursor.moveToLast();
cursor.getCount() always give same integer (1) or current position of cursor.
Code :
private String[] allPushColumns = { MySQLiteHelper.COLUMN_PUSH_ID,
MySQLiteHelper.COLUMN_PUSH_TITLE, MySQLiteHelper.COLUMN_PUSH_CONTENT, MySQLiteHelper.COLUMN_PUSH_TIME,
MySQLiteHelper.COLUMN_PUSH_TYPE, MySQLiteHelper.COLUMN_PUSH_MSG_ID};
public boolean checkUniqueId(String msg_id){
Cursor cursor = database.query(MySQLiteHelper.TABLE_PUSH,
allPushColumns, MySQLiteHelper.COLUMN_PUSH_MSG_ID + "=?", new String [] { msg_id }, null, null, MySQLiteHelper.COLUMN_PUSH_ID +" DESC");
if(cursor.getCount() <= 0){
return false;
}
return true;
}
Here's a simple solution based on a combination of what dipali and Piyush Gupta posted:
public boolean dbHasData(String searchTable, String searchColumn, String searchKey) {
String query = "Select * from " + searchTable + " where " + searchColumn + " = ?";
return getReadableDatabase().rawQuery(query, new String[]{searchKey}).moveToFirst();
}
because of possible data leaks best solution via cursor:
Cursor cursor = null;
try {
cursor = .... some query (raw or not your choice)
return cursor.moveToNext();
} finally {
if (cursor != null) {
cursor.close();
}
}
1) From API KITKAT u can use resources try()
try (cursor = ...some query)
2) if u query against VARCHAR TYPE use '...' eg. COLUMN_NAME='string_to_search'
3) dont use moveToFirst() is used when you need to start iterating from beggining
4) avoid getCount() is expensive - it iterates over many records to count them. It doesn't return a stored variable. There may be some caching on a second call, but the first call doesn't know the answer until it is counted.
Try to use cursor.isNull method.
Example:
song.isFavorite = cursor.isNull(cursor.getColumnIndex("favorite"));
You can use like this:
String Query = "Select * from " + TABLE_NAME + " where " + Cust_id + " = " + cust_no;
Cursor cursorr = db.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursorr.close();
}
cursor.close();
private boolean checkDataExistOrNot(String columnName, String value) {
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String query = "SELECT * FROM" + TABLE_NAME + " WHERE " + columnName + " = " + value;
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
if (cursor.getCount() <= 0) {
cursor.close();
return false; // return false if value not exists in database
}
cursor.close();
return true; // return true if value exists in database
}
I prefer to do it this way because it's fast and less expensive than other methods:
Cursor cursor = db.rawQuery("SELECT 1 FROM table WHERE condition = 1 LIMIT 1", null);
try {
if (cursor.moveToNext()) {
//Record exists
} else {
//Record doesn't exists
}
} finally {
cursor.close();
}
My version:
public boolean isTitleExists(String title, String type) {
int isExists = 0;
try {
String query = "SELECT EXISTS (SELECT 1 FROM titles WHERE title = ? and type = ?)";
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, title);
statement.setString(2, type);
ResultSet rs = statement.executeQuery();
rs.next();
isExists = rs.getInt(1);
rs.close();
statement.close();
} catch (SQLException e) {
Common.console("isTitleExists error: " + e.getMessage());
}
return isExists == 1;
}
I have created an application to insert data to sq-lite . i want if i enter same data again it should give e toast massage and then it only update that data not re-insert.
what should i do.....
now data is been re-inserted
method code of SQLiteOpenHelper.....
public void insertdata(String name,String ph,String area){
ContentValues cv=new ContentValues();
cv.put("name", name);
cv.put("phone", ph);
cv.put("area", area);
sd=this.getWritableDatabase();
sd.insert("location", null, cv);
sd.close();
method use in Activity class......
public void onClick(View v) {
// TODO Auto-generated method stub
help=new MyHelper(getApplicationContext());
help.getWritableDatabase();
String myname=name.getText().toString();
String call=phone.getText().toString();
String myarea=area.getText().toString().trim();
help.insertdata(myname, call, myarea);
Toast.makeText(getApplicationContext(), "data saved ", Toast.LENGTH_SHORT).show();
}
});
The data is being reinserted because you're methods never check to see if it already exists in the databse. You need to add a query for some unique combination - probably name and phone number. If that query returns a result you can prompt the user to enter the data.
String query = "SELECT * FROM " + TABLE_NAME + " WHERE name = " + name;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
if(cursor != null && cursor.moveToFirst()){ //if cursor has entry then don't reinsert
//prompt user with dialog
} else {
//insert data
}
Also you cannot use a Toast for this. What you want is a Dialog. If the data exists you can display a custom Dialog to the user that you could use to allow them to (1) enter new data (2) edit existing data (3) choose to reinsert the data they are posting. A Toast will just display a message to them like - "reinserting data". It does not sound like that is the functionalty you want to achieve.
To update the database you can just use an update statment depending on what fields you want to change.
String query = "UPDATE " + TABLE_NAME + " SET";
if(!name.isEmpty(){
query += " name = " + name;
}
if(!phone.isEmpty(){
query += " phone = " + phone;
}
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(CREATE_CONTACTS_TABLE)
I put the if statments in to check for which fields are being changed and add them to the query accordingly. In the alternative you could use something like this
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
While I havnet modified it to fit your example you can see the basic approach. Hhere you can use conditionals to check if values are being supplied, if they are you add them to the ContentVlues list which will update them in the DB.
You can try something like this:
ContentValues values=new ContentValues();
cv.put("name", name);
cv.put("phone", ph);
cv.put("area", area);
if (db == null) {
db = getWritableDatabase();
}
if (isNameExists(name)) { //check if name exits
id = db.update(TABLE_NAME, values, name + " = ?",
new String[] {name});
} else {
id = db.insert(TABLE_NAME, null, values);
}
public boolean isNameExists(String name) {
Cursor cursor = null;
boolean result = false;
try {
String[] args = { "" + name };
StringBuffer sbQuery = new StringBuffer("SELECT * from ").append(
TABLE_NAME).append(" where name=?");
cursor = getReadableDatabase().rawQuery(sbQuery.toString(), args);
if (cursor != null && cursor.moveToFirst()) {
result = true;
}
} catch (Exception e) {
Log.e("AppoitnmentDBhelper", e.toString());
}
return result;
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Fetch data in database table insert it if not exist else return the row id
I try to fetch if data exist in database table, if yes I should get the row id else I insert it in the table this my code
public int finddate(String date){
int id=0;
AndroidOpenDbHelper androidOpenDbHelperObj = new AndroidOpenDbHelper(this);
SQLiteDatabase sqliteDatabase = androidOpenDbHelperObj.getWritableDatabase();
Cursor cursor = sqliteDatabase.rawQuery("SELECT _id FROM " +
AndroidOpenDbHelper.TABLE_DATE + " where " +
AndroidOpenDbHelper.COLUMN_NAME_DATE + " = " + date,
null);
startManagingCursor(cursor);
if (cursor != null) {
if( cursor.moveToFirst() ) {
id = cursor.getInt(cursor.getColumnIndex("_id"));
}
} else {
id=0;
}
sqliteDatabase.close();
return id;
}
when i try with an existing item I get the result of this method =0 and the item is inserted in the table,
how can I do this?
The date is not being correctly escaped. The safest and cleanest way to resolve it is to pass the date value as a parameter, rather than embedding it in the query.
You can also tidy up the cursor management quite a bit. You don't need to check for a null cursor, as an exception will be thrown if the query fails. Also, you don't need to set id = 0 as you've already done that at the start. This is much simpler:
Cursor cursor = sqliteDatabase.rawQuery("SELECT _id FROM " +
AndroidOpenDbHelper.TABLE_DATE + " where " +
AndroidOpenDbHelper.COLUMN_NAME_DATE + " = ?",
new String[] { date } );
if ( cursor.moveToFirst() ) {
id = cursor.getInt(cursor.getColumnIndex("_id"));
}
cursor.close();
sqliteDatabase.close();
Your query should look like this:
Cursor cursor = sqliteDatabase.rawQuery("SELECT _id FROM " + AndroidOpenDbHelper.TABLE_DATE + " where "+ AndroidOpenDbHelper.COLUMN_NAME_DATE+ " =\'"+date+"\'", null);
startManagingCursor(cursor);
cursor.moveTofirst();
if (cursor.getCount() > 0) {
id = cursor.getInt(cursor.getColumnIndex("_id"));
}
} else {
id=0;
}