I am trying to change a single value in a coloumn in android sqlite.
but i am not getting the result. My db query is given below
public Cursor update_MaxCrAmnt(String maxcramount, String accId){
return db.rawQuery("UPDATE AccMaster SET Max_CrAmt=? WHERE Acc_No=? AND Bal_Type=?", new String[] {maxcramount, accId, "Cr"});
}
This method calling code is given below, amnt and accid are string values.
try {
db.open();
db.update_MaxCrAmnt(amnt,accid);
db.close();
} catch (Exception e) {
// TODO: handle exception
Log.e("Update error", ""+e.getMessage());
}
Need your help.. Thanks in advance.
NB:Please Dont Use this method as there is chance of SQL injection when do like this
String update = "UPDATE AccMaster SET Max_CrAmt = '"+ maxcramount +"' WHERE accId = " + accId +"AND Bal_Type= Cr";
db.execSQL(update);
Related
Currently We have one application in which we are receiving many crash reports while deleting record from database .
Here is method in which app is crashing.
public int deleteGroupMap(String nickName) {
SQLiteDatabase database = this.getWritableDatabase();
try {
return database.delete(TABLE_NAME_GROUP_MAP, COLUMN_GMAP_NICK_NAME + " = '" + nickName + "'", null);
} catch (Exception e) {
e.printStackTrace();
} finally {
database.close();
}
return 0;
}
but we am getting following exception:
android.database.sqlite.SQLiteException: near "adz": syntax error
(code 1): , while compiling: DELETE FROM groups_map WHERE
gmap_nick_name = ''adz.'
Any help will be appreciated.
Look at delete signature:
int delete (String table, String whereClause, String[] whereArgs)
Third argument is where args:
You may include ?s in the where clause, which will be replaced by the
values from whereArgs. The values will be bound as Strings.
It's automatically escaped, so there is no need to put quotes (', ") manually.
Use where args instead of strings concating:
database.delete(TABLE_NAME_GROUP_MAP, COLUMN_GMAP_NICK_NAME + " = ?", new String[] { nickName });
Try Like This
public int deleteGroupMap(String nickName) {
SQLiteDatabase database = this.getWritableDatabase();
try {
database .execSQL("DELETE FROM "+ TABLE_NAME_GROUP_MAP + " WHERE " + COLUMN_GMAP_NICK_NAME + " = "+nickName+"");
database .close();
} catch (Exception e) {
e.printStackTrace();
} finally {
database.close();
}
return 0;
}
Try this
return database.delete(TABLE_NAME_GROUP_MAP, COLUMN_GMAP_NICK_NAME + "= ?" , new String[]{Long.toString(nickName)});
You should also use parameter markers because appending values directly is error prone when the source contains special characters.
try following because it will also prevent SQL injections to your app
database.delete(TABLE_NAME_GROUP_MAP, COLUMN_GMAP_NICK_NAME + "=?", new String[]{String.valueOf(nickName));
I want to check the data in SQLite if already exist can update or else insert.I am checking code like this what i mentioned below.
Code:
public long addmenus(String navigationdrawer,String optionname)
{
SQLiteDatabase menus=this.getWritableDatabase();
try {
ContentValues values=new ContentValues();
values.put(HEADER_NAME,navigationdrawer);
values.put(CHILD_NAME,optionname);
// menus.insert(TABLE_NAME,null,values);
// String owner=optionname;
Cursor cursor = menus.rawQuery("select * from TABLE_NAME where CHILD_NAME ='"+ optionname +"'", null);
if(cursor.getCount()<1)
{
//execute insert query here
long rows = menus.insert(TABLE_NAME, null, values);
return rows;
// return rows inserted.
}
else
{
//Perform the update query
String strFilter = "CHILD_NAME" + optionname;
long updaterow=menus.update(TABLE_NAME,values,strFilter,null);
return updaterow;
// return rows updated.
}
// menus.close();
} catch (Exception e) {
return -1;
}
finally {
if (menus != null)
menus.close();
}
}
My activity:
I converted whole json data into string object then insert into SQLite.
String productpage=jsonObject.toString();
db.addmenus(productpage,"Navigationmenus");
But It doesn't work.It couldn't insert into sqlite.
Anyone solve this problem Glad to appreciate.
Thanks in advance
You can user insertWithOnConflict() like this
db.insertWithOnConflict(TABLE, null, yourContentValues, SQLiteDatabase.CONFLICT_REPLACE);
You can use refer this Link. That link explains how to find the email address available in a table or not, you can change the column name, table and pass the values according. In your scenario you want to check the whether the name exists already or not, so you must pass which name you want to find. If the name is there then this method will return true or false. You can validate whether you had to insert or update according the response.i.e., false means you had to insert, otherwise if it is true means then you had to update.
you should use replace into
REPLACE INTO table(...) VALUES(...);
Question is not much clear but, i think you want to check either data/record is inserted in SQLite or not. you will need to define some extra variable long rowInserted insert() method returns the row ID of the newly inserted row, or -1 when an error occurred.
menus.insert(TABLE_NAME, null, values);
long rowInserted = db.insert(AddNewPhysicalPerson, null, newValues);
if(rowInserted != -1)
Toast.makeText(myContext, "New row added :" + rowInserted, Toast.LENGTH_SHORT).show();
else
Toast.makeText(myContext, "Something wrong", Toast.LENGTH_SHORT).show();
Updated
check either data is in table or column? for this you use this code
public boolean Exists(String id){
Cursor res = getAllData();
int count=0;
while (res.moveToNext()){
String email =res.getString(3);
if(email.equals(id)){
count++;
}
}
if(count==0){
return false;
} else{
return true;
}
}
Second you asking about json first store all data in any List run time and get string from it then you are able to store in SQlite
try {
items = jsonObject.getJSONArray("myjsonattribute");
List<MyAnySetterGetter> mList = new ArrayList<MyAnySetterGetter>();
for (int i = 0; i < items.length(); i++) {
JSONObject c = items.getJSONObject(i);
String mfilename = c.getString("myjsonattribute2");
mList.add(mfilename);
}
} catch (JSONException e) {
//e.printStackTrace();
}
then use above list to insert data from list to SQLite
like
String str1 = mList.get(position).getMYITEM1();
String str2 = mList.get(position).getMYITEM2();
insert str1 and str2 in SQLite hope you will get idea.
you should
set key for the table, then
insert(if the key existed it will not insert anymore), then
update all row.
Following is my code for update record done.
try {
String str_edit = edit_note.getText().toString();
Toast.makeText(getApplicationContext(), str_edit,
Toast.LENGTH_LONG).show();
Toast.LENGTH_LONG).show();
String rawQuery="UPDATE " + GlobalVariable.getstr_tbl_name()
+ " SET note = '" + str_edit + "' where name = '"
+ str + "' ";
db.execSQL(rawQuery);
} catch (Exception e) {
System.out.println(e.getMessage());
}
Code for Display:
try {
Cursor note_cursor = db.query(GlobalVariable.getstr_tbl_name(),
new String[] { "note" + " as note" }, "name" + "=?",
new String[] { GlobalVariable.getstr_food_name() }, null,
null, null);
if (note_cursor.moveToFirst()) {
int notecol = note_cursor.getColumnIndex("note");
do {
String str = note_cursor.getString(notecol);
Toast.makeText(getApplicationContext(), str,
Toast.LENGTH_LONG).show();
edit_note.setText(str);
} while (note_cursor.moveToNext());
}
}
catch (Exception e) {
System.out.println(e.getMessage());
}
I am getting all variable value i.e global variables and all but update does not reflects on table.
What wrong i am done?
whenever we try to update our database then just clean and uninstall your app then again install may be some changes not take place when we don't uninstall it if u find correct then tell other wise we will see the next
Should
int notecol = note_cursor.getColumnIndex("name");
instead be
int notecol = note_cursor.getColumnIndex("note");
since in the first block of code you are updating note..
The problem is that you try to update your DB using a rawQuery method instead of a execSql. RawQuery is intended to retrieve data from your database, while execSql lets you
Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.
You can also consider to use public int update (String table, ContentValues values, String whereClause, String[] whereArgs) method.
I wanted to update my existing table with new values but some of them are fresh. I have written code for updating the table, but how can I do both operations(update & insert) simultaneously.
Just use replace() method in SQLiteDatabase. Its simply insert a new row if no row with same key is not exists in database. Otherwise it replaces the existing row.. Its simple than other ways.. For more info refer the documentation..
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
Try something like this:
String username="xyzName";
Cursor cur_user = my_db.rawQuery("SELECT _id from user_info where user_name ='"
+ username + "'", null);
if (cur_user.getCount() > 0) {
// User exists. Update information in database.
ContentValues cvUserInfo = new ContentValues();
cvUserInfo.put("status", status_id);
String whereClause = "user_name = '" + username + "'";
try {
my_db.update("user_info", cvUserInfo, whereClause, null);
} catch (Exception e) {
e.printStackTrace();
}
} else {
// Insert the information in database.
ContentValues cvUserInfo = new ContentValues();
cvUserInfo.put("status", status_id);
cvUserInfo.put("user_name", username);
my_db.insert("user_info", null, cvUserInfo);
}
You will need to have one column except id, on which you can check. I had user name as a unique column to check for existing record.
Hope this helps.
I'm new to android ... i have developed a Database application , were i'm able to insert the textfield details , but i want to delete the specific row , i need to search by name and delete the user.
can someone help me on this :
My DB code is:
public void deleteRow(String firstname)
{
try {db.delete(TABLE_NAME,TABLE_ROW_ONE + "=?" + new String[]{firstname},null);}
catch (Exception e)
{
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
Activty code is :
deleteButton.setOnClickListener
(
new View.OnClickListener()
{
#Override public void onClick(View v) {deleteRow();}
}
);
private void deleteRow()
{
try
{
db.deleteRow(textFieldOne.getText().toString());
updateTable();
emptyFormFields();
}
catch (Exception e)
{
Log.e("Delete Error", e.toString());
e.printStackTrace();
}
}
textFieldOne is the first name of the user.
can someone help me on this ..
Remove the null Argument from your delete method...
do like this ---->
db.delete(TABLE_NAME,TABLE_ROW_ONE + "=?" + new String[]{ firstname });
It will work fine...
I think you've misunderstood the purpose of ? in Android+sqlite.
the ? are used as a placeholder which are then replaced with the strings you pass as the third argument to delete and other similar database functions on Android.
In your code you're setting the selection argument a combination of the selection string and the selection arguments string array.
Changing the code from
/* ... */ TABLE_ROW_ONE + "=?" + new String[]{firstname},null);
to
/* ... */ TABLE_ROW_ONE + "=?", new String[]{firstname});
should do the trick.
You can also just say
db.delete(TABLE_NAME, TABLE_ROW_ONE + "='" + firstname + "'", null);
if you want to but the purpose of the ? is to do some kind of caching with the queries so they'd be faster next time.