sqlite error in android - android

I am getting the value from webservice. I am storing in sqlite. While storing in sqlite, I am getting an error. even I replaced single quote with "\'". Which characters are not supported in sqlite?
My error is:
03-26 13:22:22.478: WARN/System.err(311): android.database.sqlite.SQLiteException: near "s": syntax error:
My insert statement is:
myDB.execSQL("INSERT INTO "+TableName
+"("+fieldname+")"
+" VALUES ('"+(homevalue)+"');");
Can anybody tell what to do or give an example?

there is a name which is like "name's" i.e this single quote is problem

Maybe one of your string TableName, fieldname or homevalue contains some quotation. print out the query first and see.

I am just a beginner,
but i think you should write it like this:
"INSERT INTO " + tableName + "(" + feildName + ") VALUES ('" + homeValue + "');"
you put () around the homeValue

Related

Using LIKE and LIMIT in sqlite queries in Android

I'm writing a function for an Android app, that should get the first 8 entries (names of cities) of a database which are matching a string.
This is my query:
Cursor cursor = database.rawQuery(
"SELECT " + CITIES_NAME +
" FROM " + TABLE_CITIES +
" WHERE " + CITIES_NAME +
" LIKE " + String.format("%s%%", nameLetters) +
" LIMIT " + 8
, null);
This is the resulting error:
android.database.sqlite.SQLiteException: near "LIMIT": syntax error (code 1): , while compiling: SELECT city_name FROM CITIES WHERE city_name LIKE berl% LIMIT 8
I have already checked out other questions on the platform, but could not find any solution helping me out. The database is tested and created correctly and also the search entry is in the database.
Could anybody help?
WARNING: You should NOT use string concatenation with the + operator to insert user input in a SQL query.This leaves your app open to a SQL injection attack. I cannot emphasize this enough. Mitigating this common security flaw should be a top priority for all database developers.
Instead, you should use the ? place holder syntax:
String query = "SELECT " + CITIES_NAME +
" FROM " + TABLE_CITIES +
" WHERE " + CITIES_NAME +
" LIKE ?" +
" LIMIT 8";
String[] args = {nameLetters + "%%"};
Cursor cursor = database.rawQuery(query, args);
Even if the database is small and only used for your individual app, it is best to make this syntax a habit. Then when you work on larger, more critical databases, you won't have to worry about this issue as much.
This also has the advantage that it quotes the input for you. You completely avoid the error which you encountered that prompted the original question.
For the sake of completeness I'll turn my comment into an answer, to hopefully help anyone else who may have this issue.
Think you need quotes around the like string eg
SELECT city_name FROM CITIES WHERE city_name LIKE 'berl%' LIMIT 8

Error on inserting sequential number in MySQL

I have to insert sequential number from 1 to N in an empty column in a database. Android Studio is giving me the following error when I run my code:
Caused by: android.database.sqlite.SQLiteException: unrecognized token: ":" (code 1): , while compiling: SELECT #i:=0; UPDATE table_name SET column_one = #i:=#i+1;
My line of code:
db.execSQL("SELECT #i:=0; UPDATE table_name SET column_one = #i:=#i+1;");
(Please note when I change MySQL statement between parenthesis the code runs and gets executed)
Source of SQL code:
Insert sequential number in MySQL
I'm new in Java, Android Studio and MySQL.
What am I missing here?
Help me to understand why MySQL #i:=#i+1 expression is not running properly in Android Studio.
Thanks in advance.
Because android database is using sqlite,but sqlite dose not supported “#”,if you want batch processing ,I suggest you use Java
Try this .
database.execSQL("SELECT " + #i + " :=0 ; UPDATE table_name SET column_one = " + #i + " := " + #i "+1;");

Error: No such column name

I have been trying to execute a query:-
String selectQuery="SELECT "+ROLE+" FROM "+TABLE_EMPLOYEE+ " WHERE "+USER_ID+ "='"+userId+"' AND "+PASSWORD+"='"+password+"';";
cursorObj = dbObj.rawQuery(selectQuery, null);
This will result to:-
SELECT Role FROM employee WHERE User_Id='HondaSE' AND Password='456';
The logcat says:-
01-08 12:05:10.070: W/System.err(9318): android.database.sqlite.SQLiteException: no such column:
HondaQE: , while compiling: SELECT Role FROM employee WHERE User_Id=HondaQE AND Password=123;
I have tried to run the query with double quotes as well, for userId and password. resulting in:-
SELECT Role FROM employee WHERE User_Id="HondaSE" AND Password="456";
However both the queryies work perfectly fine when executed in SQLITE Data browser.
Both respond with same error.
Your logcat shows as below.
while compiling: SELECT Role FROM employee WHERE User_Id=HondaQE AND Password=123;
there is no single quotes around strings in User_Id=HondaQE AND Password=123.
You weren't compiling your raw query correctly. I would advise you to use "query" instead and use selection args to avoid these mistakes and possible sql injections.
Rewrite like this
String selectQuery="SELECT "+ROLE+" FROM TABLE_EMPLOYEE " WHERE USER_ID ='" + userId + "' AND PASSWORD = '" +password+ "'";
I had the closed the db before accessing the cursor. This was the error.
After accessing the cursor, the db is to be closed. Error solved.

How to use INSERT OR REPLACE correctly?

I was originally looking for an INSERT OR UPDATE ability in SQLite but searches showed similar question askers being pointed to using INSERT OR REPLACE.
I'm obviously misunderstanding how this works and obviously I can't use WHERE as I'm getting the following SQLiteException...
08-12 01:38:22.973: ERROR/AndroidRuntime(29242): FATAL EXCEPTION: main
08-12 01:38:22.973: ERROR/AndroidRuntime(29242): android.database.sqlite.SQLiteException:
near "WHERE":
syntax error:
INSERT OR REPLACE INTO SERVERS (
server_name,
service_uri_mobile,
service_uri_wifi,
valid_ssids,
username,password
) VALUES (
'Default',
'http://myserver.com:8790/',
'http://192.168.1.1:8790/',
'[]',
'admin',
'password')
WHERE server_name='Default'
The SQL string I'm using is as follows...
String UpdateString = "INSERT OR REPLACE INTO SERVERS " +
"(server_name,service_uri_mobile,service_uri_wifi,valid_ssids,username,password) VALUES ('" +
locater.getServerName() + "','" +
locater.getServiceUriMobile().toString() + "','" +
locater.getServiceUriWifi().toString() + "','" +
locater.getValidSsids().toString() + "','" +
locater.getUsername() + "','" +
locater.getPassword() + "') " +
"WHERE server_name='" + locater.getServerName() + "'";
I've looked at this page explaining REPLACE but don't quite understand it. How would I re-write the above SQLite command and have it only try to replace the record where the server_name matches (i.e., the equivalent of a WHERE clause)?
Looking at the documentation (and mirroring the comments below the question), REPLACE should be used when UPDATEing (or in other words changing) columns that are UNIQUE. To wit:
REPLACE
When a UNIQUE constraint violation occurs, the REPLACE algorithm
deletes pre-existing rows that are causing the constraint violation
prior to inserting or updating the current row and the command
continues executing normally.
http://sqlite.org/lang_conflict.html

Android insert into sqlite database

I know there is probably a simple thing I'm missing, but I've been beating my head against the wall for the past hour or two. I have a database for the Android application I'm currently working on (Android v1.6) and I just want to insert a single record into a database table. My code looks like the following:
//Save information to my table
sql = "INSERT INTO table1 (field1, field2, field3) " +
"VALUES (" + field_one + ", " + field_two + ")";
Log.v("Test Saving", sql);
myDataBase.rawQuery(sql, null);
the myDataBase variable is a SQLiteDatabase object that can select data fine from another table in the schema. The saving appears to work fine (no errors in LogCat) but when I copy the database from the device and open it in sqlite browser the new record isn't there. I also tried manually running the query in sqlite browser and that works fine. The table schema for table1 is _id, field1, field2, field3.
Any help would be greatly appreciated. Thanks!
Your query is invalid because you are providing 2 values for 3 columns. Your raw query should look like:
sql = "INSERT INTO table1 (field1, field2) " +
"VALUES (" + field_one + ", " + field_two + ")";
although your schema contains three fields. By the way, you can see the log to see the actual error reporting from sqlite.
The right answer is given by the CommonsWare in comments. You should be using execSql() instead of rawQuery(). And it works like a charm.
I thought it would be useful for others, not to have to dig through the comments to find the right answer.
Since it is a string values you forgot "'" to add...this query will surely work, i tested
sql = "INSERT INTO table1 (field1, field2) " +
"VALUES ('" + field_one + "', '" + field_two + "')";
I changed my code to use myDataBase.insert() instead of rawQuery() and it's working. I'm not sure why the actual sql query didn't work though, so if anyone can shed some light on that I'd still appreciate it.

Categories

Resources