i am using the below code to insert row to my db. every thing is fine but this method does not save row to the db. what is wrong with this code :
public void insert(Restaurant rest) {
String[] args = { String.valueOf(rest.getId()), rest.getName(),
rest.getDescription(), rest.getAddress(), rest.getTel1(),
rest.getTel2(), rest.getTel3(), rest.getEmail(),
String.valueOf(rest.getCategory()),
String.valueOf(rest.getRegion()) };
m_db.rawQuery(
"INSERT OR REPLACE INTO restaurant(id,name,description,address,tel1,tel2,tel3,email,category,region) VALUES(?,?,?,?,?,?,?,?,?,?)",
args);
}
Use execSQL() and not rawQuery() for raw SQL that modifies the database.
rawQuery() alone won't execute the SQL; you'd need to call one of the moveTo...() methods on the returned Cursor to execute it.
Related
I want to know the difference between inserting data using ContentValues and inserting data using Raw SQL in SQLlite(Android), Is there a advantage using content values?
To perform insert, read, delete, update operation there are two different ways:
Write parameterized queries (Recommended)
Write raw queries
Parameterized Queries: These are those queries which are performed using inbuilt functions to insert, read, delete or update data. These operation related functions are provided in SQLiteDatabase class.
Raw Queries: These are simple sql queries similar to other databases like MySql, Sql Server etc, In this case user will have to write query as text and passed the query string in rawQuery(String sql,String [] selectionArgs) or execSQL(String sql,Object [] bindArgs) method to perform operations.
Important Note: Android documentation don’t recommend to use raw queries to perform insert, read, update, delete operations, always use SQLiteDatabase class’s insert, query, update, delete functions.
Following is an example of raw query to insert data:
public void insertItem(Item item) {
String query = "INSERT INTO " + ItemTable.NAME + " VALUES (0,?,?)";
SQLiteDatabase db = getWritableDatabase();
db.execSQL(query, new String[]{item.name, item.description});
db.close();
}
While using raw queries we never come to know the result of operation, however with parameterized queries function a value is returned for success or failure of operation.
Insert: To perform insert operation using parameterized query we have to call insert function available in SQLiteDatabase class. insert() function has three parameters like public long insert(String tableName,String nullColumnHack,ContentValues values) where tableName is name of table in which data to be inserted.
Here is simple example:
//Item is a class representing any item with id, name and description.
public void addItem(Item item) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name",item.name);
// name - column
contentValues.put("description",item.description);
// description is column in items table, item.description has value for description
db.insert("Items", null, contentValues);//Items is table name
db.close();
}
For more Information see this Link
I got the data from webservice and insert them to database in activity onCreate() function. the code is as below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.contact_person);
RunningService runningService = new RunningService();
runningService.insert(staff);
initView();
}
And the the code of insert() is as below:
public void insertAllStaff(Staff staff){
ContentValues values = new ContentValues();
values.put("name", staff.getName());
Uri uri = contentResolver.insert(CONTENT_URI, values);
}
Every time that I go into this activity, it will insert data to database, the data are the same.
Is there a method that I can go into this activity and it doesn't insert the same data to database?
If you don't want repeated values for your table you have to define a UNIQUE index for the field you feel is "unique".
You do that at table CREATE time, or you can create indexes using the ALTER SQL statement.
SQLite supports the INSERT NOT EXISTS syntax.
INSERT INTO MyTable(id,text)
SELECT 123, 'Helloworld'
WHERE NOT EXISTS(SELECT 123 FROM MyTable WHERE id = 123');
Please use this syntax for performance.
Which content provider are you using with your resolver? You might need to change it and use something else which uses the above SQL statement.
My Java code Update Data base Table
String qq="UPDATE ChallanItems SET Recieve ="+str+" WHERE ItemNo = "+code;
Log.d("Qry", qq);
myDbHelper.updatequery(qq);
updatequery method
public void updatequery(String qry)
{
Cursor c = myDataBase.rawQuery(qry, null);
Log.d("Up", ""+c.getCount());
}
When i updated Data base the count return 0 and table not updated
I am using this Also but not work
String qq="UPDATE ChallanItems SET Recieve ="+str+" WHERE ItemNo = "+"'"+code+"'";
Please Help Me how i can fix this problem
Thanks In Advance
Use execSQL() for such SQL and not rawQuery().
rawQuery() just compiles the SQL but does not run it. You'd need to call one of the move...() methods on the returned Cursor to execute a step of the compiled SQL program.
execSQL() both compiles and runs the SQL program.
There's also possibly a syntax problem with your literals - use parameters i.e. ? placeholders in SQL and String[] bind arguments to be safe.
To update sqlite query change
Cursor c = myDataBase.rawQuery(qry, null);
to this
myDataBase.execSQL(qry);
try to use this:
ContentValues values = new ContentValues();
values.put("Recieve", str);
db.update("ChallanItems", values2, "ItemNo = ?", new String[] { code });
This is my method to delete a row from the database where appointment_date is equal to a date that was passed in
public void deleteAllAppointments(String date) {
SQLiteDatabase db = this.getWritableDatabase();
String deleteAllQuery = "DELETE FROM " + TABLE_APPOINTMENTS + " WHERE appointment_date = '" + date + "'";
db.rawQuery(deleteAllQuery, null);
Log.d("Query: ", deleteAllQuery);
}
I then use it like this
//Database (DatabaseHandler is the one that contains all database methods)
final DatabaseHandler database = new DatabaseHandler(this);
//This happens when button is clicked, it is tested an executes with every chick,
//#param selectedDate is a string like "18/03/2014"
database.deleteAllAppointments(selectedDate);
It executes and query looks like this
DELETE FROM appointments WHERE appointment_date = '18/03/2014'
However row with appointment_date = '18/03/2014' is not deleted.
I'm sure database is set up correctly as I have working methods with it and all information is received from there in correct format.
NOTE: Adding "*" to "DELETE * FROM..." returns a fatal syntax error.
rawQuery() just compiles the SQL but does not run it. To actually run it, use either execSQL() or call one of the moveTo...() methods on the cursor returned by rawQuery().
For further info, see What is the correct way to do inserts/updates/deletes in Android SQLiteDatabase using a query string?
For tasks such as insert or delete there are really great "convenience methods" like the [delete method](http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#delete(java.lang.String, java.lang.String, java.lang.String[])) already built in to the database.
public int delete (String table, String whereClause, String[] whereArgs)
As to why your current approach would fail, it could be something as simple the format of the column you're trying to delete not matching (e.g. you have created the table as a date value and not a string).
In any case, using the built in delete method is easier because it will notify you when it fails by returning the number of rows affected by the delete. rawQuery just returns a cursor, which you would then have to get the result from to see if it worked.
Are you sure your data value is in European format of day/month/year ala your query value of 18/03/2014 and maybe its not US style of month/day/year: 03/18/2014.
Not trying to be US-centric but that was my first thought.
Otherwise, definitely look at SQLiteDatabase.delete:
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#delete(java.lang.String, java.lang.String, java.lang.String[])
i'm unable to delete row in a table using sqlite 3.In my code i would like to compare two
values an then delete the data in a table but it is not possible please help me.
while(authCur.moveToNext())
{
db.delete("auth_tab",authCur.getString(0)+"=?" , new String[] { user });
db.delete("auth_tab", null, null);
}
Deleting data
Once data is no longer needed it can be removed from the database with the delete() method. The delete() method expects 3 parameters, the database name, a WHERE clause, and an argument array for the WHERE clause. To delete all records from a table pass null for the WHERE clause and WHERE clause argument array.
db.delete("auth_tab", "authCur.getString(0)=?", new String[] {user);
Simply call the delete() method to remove records from the SQLite database. The delete method expects, the table name, and optionally a where clause and where clause argument replacement arrays as parameters. The where clause and argument replacement array work just as with update where ? is replaced by the values in the array.
or
public void deleteContact(long id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(auth_tab, KEY_USER + " = ?",
new String[] { user) });
db.close();
}
WATCH more, and you tube video, how to delete.