E/SQLiteLog: (1) near "(": syntax - android

I try to save data in my app database for a while but i still get the same issue. Here is what my code looks like.
In the database page:
public void insererTrajetTest (String et_VilleD, String et_VilleA, String
et_LieuDepart, String et_LieuArrivee,String et_dateDepartAller, String
et_heureDepartAller, String et_flexibilite, String et_bagage, String et_detour,
String et_iduser, String et_trajet, String et_commentaire, String et_place,
String et_dateArriveeAller, String et_heureArriveeAller, String et_prix, String
et_distance, String et_duree) {
db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME3;
Cursor cursor = db.rawQuery(query, null);
ContentValues values = new ContentValues();
values.put(COLUMN_VILLE_DEPART, et_VilleD);
values.put(COLUMN_VILLE_ARRIVEE, et_VilleA);
values.put(COLUMN_LIEU_DEPART, et_LieuDepart);
values.put(COLUMN_LIEU_ARRIVEE, et_LieuArrivee);
values.put(COLUMN_DATE_DEPART, et_dateDepartAller);
values.put(COLUMN_HEURE_DEPART, et_heureDepartAller);
values.put(COLUMN_FLEXIBILITE, et_flexibilite);
values.put(COLUMN_BAGAGE, et_bagage);
values.put(COLUMN_DETOUR, et_detour);
values.put(COLUMN_ID_CHAUFFEUR, et_iduser);
values.put(COLUMN_TRAJET, et_trajet);
values.put(COLUMN_COMMENTAIRE, et_commentaire);
values.put(COLUMN_PLACES_PROPOSEES, et_place);
values.put(COLUMN_PLACES_DISPONIBLES, et_place);
values.put(COLUMN_DATE_ARRIVEE, et_dateArriveeAller);
values.put(COLUMN_HEURE_ARRIVEE, et_heureArriveeAller);
values.put(COLUMN_PRIX, et_prix);
values.put(COLUMN_DISTANCE, et_distance);
values.put(COLUMN_DUREE, et_duree);
db.insert(TABLE_NAME3, null, values);
Log.d("Base de données", "Un nouveau voyage a été créé...");
db.close();
cursor.close();
}
However I always get the followings in the logcat:
09-18 22:15:49.986 4108-4427/cm.opep.opep E/SQLiteLog: (1) near "(": syntax error
09-18 22:15:49.990 4108-4427/cm.opep.opep E/SQLiteDatabase: Error inserting VilleDépart=Abong-Mbang Trajet=Abong-Mbang --> Ambam: HeureDépart=23:45 DateDépart=2018-09-28 Flexibilité=+/- 30 minutes HeureArrivée=05:59 Bagage=Petit Commentaire=Nine LieuArrivée=Er VilleArrivée=Ambam Durée=06 h 14 min DateArrivée=2018-09-29 LieuDépart=Az IDChauffeur=5 Détour=+/- 15 minutes Prix=3100 Distance(Km)=422 PlacesDisponibles=5 PlacesProposées=5
android.database.sqlite.SQLiteException: near "(": syntax error (code 1): , while compiling: INSERT INTO Voyage(VilleDépart,Trajet,HeureDépart,DateDépart,Flexibilité,HeureArrivée,Bagage,Commentaire,LieuArrivée,VilleArrivée,Durée,DateArrivée,LieuDépart,IDChauffeur,Détour,Prix,Distance(Km),PlacesDisponibles,PlacesProposées) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at cm.opep.opep.DatabaseHelper.insererTrajetTest(DatabaseHelper.java:1328)
at cm.opep.opep.fragment.BackGroundTask.doInBackground(BackGroundTask.java:56)
at cm.opep.opep.fragment.BackGroundTask.doInBackground(BackGroundTask.java:12)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Can anyone tell me what goes wrong with my code ?

I believe that the issue is with the column named Distance(Km), to use such a column name. You'd have to enclose it e.g.
Prix,`Distance(Km)`,PlacesDisponibles,
You could do this bay changing COLUMN_DISTANCE to be defined using
COLUMN_DISTANCE = "`Distance(Km)`"
This would result in :
INSERT INTO Voyage(VilleDépart,Trajet,HeureDépart,DateDépart,Flexibilité,HeureArrivée,Bagage,Commentaire,LieuArrivée,VilleArrivée,Durée,DateArrivée,LieuDépart,IDChauffeur,Détour,Prix,`Distance(Km)`,PlacesDisponibles,PlacesProposées) VALUES (
'Abong-Mbang','Abong-Mbang --> Ambam:','23:45','2018-09-28','+/- 30 minutes','05:59','Petit','Nine','Er','Ambam','06 h 14 min','2018-09-29',
'Az',5,'+/- 15 minutes',3100,422,5,5
);
Which works as per :-
INSERT INTO Voyage(VilleDépart,Trajet,HeureDépart,DateDépart,Flexibilité,HeureArrivée,Bagage,Commentaire,LieuArrivée,VilleArrivée,Durée,DateArrivée,LieuDépart,IDChauffeur,Détour,Prix,`Distance(Km)`,PlacesDisponibles,PlacesProposées) VALUES (
'Abong-Mbang','Abong-Mbang --> Ambam:','23:45','2018-09-28','+/- 30 minutes','05:59','Petit','Nine','Er','Ambam','06 h 14 min','2018-09-29',
'Az',5,'+/- 15 minutes',3100,422,5,5
)
> Affected rows: 1
> Time: 0.23s
Note for the column to exist then it's name must have been enclosed when the table was defined.
However, I'd suggest renaming the column to Distance_Km.
There are alternative enclosing characters you could also use
"Distance(Km)" i.e. enclosed in " and "
[Distance(Km)] i.e. enclosed in [ and ]
'Distance(Km)' i.e. enclosed in ' and '
This is covered at SQL As Understood By SQLite - SQLite Keywords

Related

I have a problem when dealing with the local database when adding and modifying

I have a problem when editing and adding the database
I tried to edit and search for the problem but could not find the solution
public boolean insert_dealer(get_set_db dealer){
ContentValues Values = new ContentValues();
Values.put(My_data.dealer_CLN_NMEA , dealer.getName());
Values.put(My_data.dealer_CLN_description , dealer.getDescribe());
Values.put(My_data.dealer_CLN_image , dealer.getImage());
Values.put(My_data.dealer_CLN_WHOLESALE , dealer.getWholesale());
Values.put(My_data.dealer_CLN_INDIVIDUAL , dealer.getAn_individual());
long result = database.insert(My_data.dealer_TB_NAME,null,Values);
return result != -1;
}
Logs details
2019-07-11 09:28:44.341 31418-31418/com.example.dealer E/SQLiteLog: (1) near "individual": syntax error
2019-07-11 09:28:44.348 31418-31418/com.example.dealer E/SQLiteDatabase: Error inserting image=kcc An individual=3.0 describe=othman wholesale=2.0 Name=ott
android.database.sqlite.SQLiteException: near "individual": syntax error (code 1 SQLITE_ERROR): , while compiling: INSERT INTO dealerr(image,An individual,describe,wholesale,Name) VALUES (?,?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:903)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:514)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1562)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1433)
at com.example.dealer.DatabaseAccess.insert_dealer(DatabaseAccess.java:49)
at com.example.dealer.Main2Activity.onOptionsItemSelected(Main2Activity.java:154)
Here dealer.getAn_CLN_INDIVIDUAL() returning "An individual", here you can not keep an attribute name with space. Just change it to an_individual, hope it will work.
My_data.dealer_CLN_INDIVIDUAL , dealer.getAn_individual()
The constant My_data.dealer_CLN_INDIVIDUAL which represents a column's name, has been defined as:
String dealer_CLN_INDIVIDUAL = "An individual";
A column's name must not contain spaces.
You can enclose it in square brackets to solve the problem:
String dealer_CLN_INDIVIDUAL = "[An individual]";

android.database.sqlite.SQLiteException: no such column: UPDATE

There is something wrong with my update statement. I am trying to update an user from my database, I am sure this user is in my database, but I just can't update him. I think I have a fault with my column name because the error said:
android.database.sqlite.SQLiteException: no such column: UPDATE
But I never asked for this column, nnn isn't a column at all in my scheme. Here is the statement
public void changeprofiel(String id, Profiel p){
SQLiteDatabase db = this.getWritableDatabase();
/* ContentValues contentValues = new ContentValues();
contentValues.put(COL_2_PROFIELEN, p.getUsername());
contentValues.put(COL_3_PROFIELEN, p.getFirstname());
contentValues.put(COL_4_PROFIELEN, p.getEmail());
contentValues.put(COL_5_PROFIELEN, p.getPassword());*/
// de insert methode geeft -1 terug als het niet gelukt is en de row value als het wel gelukt is
System.out.println(getProfielWid(id).getId());
// db.update(TABLE_NAME_PROFIELEN, contentValues,COL_1_PROFIELEN ="'" + id +"'",null);
db.execSQL("UPDATE "+ TABLE_NAME_PROFIELEN + " SET "+COL_2_PROFIELEN+" = "+p.getUsername()+", " +COL_3_PROFIELEN+" = "+p.getFirstname()+", "+COL_4_PROFIELEN+" = "+p.getEmail()+", "+COL_5_PROFIELEN+" = "+p.getPassword()+
" WHERE " + COL_1_PROFIELEN + "=" + id + "");
}
I also tried this way for the where closule:
" WHERE " + COL_1_PROFIELEN + "='" + id + "'");
But they give me both this error:
I/System.out: nnnnnn
E/SQLiteLog: (1) no such column: nnn
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.cedri.bcv, PID: 13908
android.database.sqlite.SQLiteException: no such column: nnn (code 1): , while compiling: UPDATE profielen SET username = nnn, firstname = nnn, email = nnn, password = xxx WHERE profile_id=nnnnnn
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1677)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1608)
at com.example.cedri.bcv.DB.DatabaseHelper.changeprofiel(DatabaseHelper.java:82)
at com.example.cedri.bcv.Activities.MainActivity.savechanges(MainActivity.java:94)
at com.example.cedri.bcv.Fragments.AccountFragment$1.onClick(AccountFragment.java:86)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6121)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
Do I need to set every value between single quotes?
You need to wrap your values with single quotes ('') if the column's type is text.
Your query should look like this:
UPDATE profielen SET username = 'nnn', firstname = 'nnn', email = 'nnn', password = 'xxx'
WHERE profile_id='nnnnnn'

How to insert a new row of table of sqlite in android?

I am working on a attendance apps for teacher. I have created database and trying to insert a new row but I am getting errors.I am giving few necessary code below.
Database creation is as:
String aquery="CREATE TABLE "+ATTENDANCE_TABLE_NAME+" ( COLUMN_DATE TEXT PRIMARY KEY );";
db.execSQL(aquery);
And ALTER the table as:
String aquery="ALTER TABLE "+ATTENDANCE_TABLE_NAME+" ADD COLUMN '"+new_col_name+"' TEXT;";
db.execSQL(aquery);
now I am inserting a row a new row as:
ContentValues Values=new ContentValues();
SQLiteDatabase db=getWritableDatabase();
// finding all column
Cursor dbCursor = db.query(ATTENDANCE_TABLE_NAME, null, null, null, null, null, null);
String[] columnNames = dbCursor.getColumnNames();
String zero="0";
for (int i=0;i<columnNames.length;i++)
{
// saving values to each specific column
if(i==0)
Values.put("COLUMN_DATE", date );
else
Values.put(columnNames[i],"'"+zero+"'");
}
check = db.insert(ATTENDANCE_TABLE_NAME, null , Values);
But I am getting this error:
05-25 18:52:23.023 19480-19480/com.example.vikas.scannerproject E/SQLiteLog: (1) near "14202": syntax error
05-25 18:52:23.023 19480-19480/com.example.vikas.scannerproject E/SQLiteDatabase: Error inserting COLUMN_DATE=2017-05-25 14202='0'
android.database.sqlite.SQLiteException: near "14202": syntax error (code 1): , while compiling: INSERT INTO CSE_OS_2017_ATTENDANCE(COLUMN_DATE,14202) VALUES (?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at com.example.vikas.scannerproject.Index_DBHandler.takingAttendance(Index_DBHandler.java:148)
at com.example.vikas.scannerproject.ScanresultActivity.takeAttendance(ScanresultActivity.java:44)
at com.example.vikas.scannerproject.ScanresultActivity.onCreate(ScanresultActivity.java:32)
at android.app.Activity.performCreate(Activity.java:6303)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
at android.app.ActivityThread.access$900(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5441)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
Please help me in insertion of new row.
Column Names in SqLite may not start with a number[0-9]. Change the column name to something like "A14202".
BTW Adding a column for each assignment may not be the best design. SqLite will only allow 2000 columns.
Column names in sqlite should be start with the Alphabet letter{A-Z,a-z}.
It should not start with numeric value.
Try this:
String aquery="ALTER TABLE "+ATTENDANCE_TABLE_NAME+" ADD COLUMN '"+"A"+new_col_name+"' TEXT;";
db.execSQL(aquery);

android.database.sqlite.SQLiteException: near ";": syntax error (code 1):

I am getting this error when I am trying to delete a record from the database. Here is the error in full
FATAL EXCEPTION: main
Process: itp231.dba.nyp.com.bloommain, PID: 12274
android.database.sqlite.SQLiteException: near ";": syntax error (code 1): , while compiling: DELETE FROM events WHERE id= ;
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
at itp231.dba.nyp.com.bloommain.EventInformationPage$1.onClick(EventInformationPage.java:135)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:163)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Looking at the log, it directed me to this line of codes (my deleteRecord() method -
private void deleteRecord() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Are you sure you want delete this person?");
alertDialogBuilder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
String id = editTextId.getText().toString().trim();
String sql = "DELETE FROM events WHERE id= " + id + ";";
db.execSQL(sql);
Toast.makeText(getApplicationContext(), "Record Deleted", Toast.LENGTH_LONG).show();
c = db.rawQuery(SELECT_SQL,null);
}
});
1 - Your id is a blank string, therefore it can't be parsed in your SQL command.
2 - If your id field is a TEXT (???), then you need to enclose it in single quotes.
3 - For SQL commands, use execSQL() instead of rawQuery() - rawQuery() only works on... queries (SELECT)
4 - And... prepared statements (or bound parameters) are a better choice. The placeholders (?) will be replaced automatically in their positional order and the quotes won't be a problem anymore (Android will handle that for you!).
You can use prepared statements
SQLiteStatement stmt = db.compileStatement("DELETE FROM events WHERE id = ?");
stmt.bindString(1, id);
stmt.execute();
try this..
db.delete("events","id=?",new String[]{Integer.toString(id)});
in which,
first paramater -> will be table name from where the deletion of data need to de done.
Second parameter -> Selection field in table.based on which field we are going to perform the deletion
Third parameter -> specifies the value,to be compare it with second paramters field if it is matched,then the particular column will be deleted.

Android - DatabaseUtils.sqlEscapeString() does not work

I want to insert "women's cloth" in the database, so I use
String name = DatabaseUtils.sqlEscapeString("women's cloth");
but it gives out put like
"'Women''s Clothing'"
and while inserting app crashes and gives
E/SQLiteLog: (1) near ",": syntax error
--------- beginning of crash -----------------
07-12 12:42:19.628 22387-22521/com.i4ustores E/AndroidRuntime: FATAL EXCEPTION: Thread-8634
android.database.sqlite.SQLiteException: near ",": syntax error (code 1):
From your simple code, I guess you create SQL statement manually.
Try using String.format:
String query = String.format("SELECT * FROM %s WHERE %s = ?",
TABLE_NAME, SEARCH_KEY);
Read more at: Local Databases with SQLiteOpenHelper
Or try using PreparedStatement like below:
PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES
SET SALARY = ? WHERE ID = ?");
pstmt.setBigDecimal(1, 153833.00)
pstmt.setInt(2, 110592)
Please be aware that the parameterIndex (i.e 1 and 2 in above code) start from 1.

Categories

Resources