syntax-error,android-sqlite,sql-insert , Android SQLiteDatabase Insert Syntax Error

Android SQLiteDatabase Insert Syntax Error


Tag: syntax-error,android-sqlite,sql-insert

I've searched around and found people with similar issues, yet not quite the same. I'm receiving an SQLite syntax error, but I cannot locate the bad syntax. Please help!

I created an SQLite Database in, seen here:

static class DatabaseHelper extends SQLiteOpenHelper{
        private static final String DATABASE_NAME = "mealdatabase";
        private static final String TABLE_INGREDIENT = "INGREDIENTS";
        private static final int DATABASE_VERSION = 1;
        private static final String UID = "_id";
        private static final String INGREDIENT_NAME = "Ingredient Name";
        private static final String SERVING_UNITS = "Serving Units";
        private static final String SPC = "Servings Per Container";
                +SERVING_UNITS+" VARCHAR(255), "+SPC+" VARCHAR(255));";

        private Context context;

        public DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            Message.message(context, "Constructor Called");

        public void onCreate(SQLiteDatabase db) {
            try {
                Message.message(context, "onCreate Called");
            } catch (SQLException e) {
                Message.message(context, ""+e);


        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            try {
                Message.message(context, "onUpgrade Called");
            } catch (SQLException e) {
                Message.message(context, ""+e);


I'm trying to insert new data into an existing SQLite Database. The database was created with no errors. However, when my insert function is called, I get the following syntax error:

03-06 20:44:27.559: E/SQLiteLog(968): (1) near "Per": syntax error
03-06 20:44:27.619: E/SQLiteDatabase(968): Error inserting Servings Per Container=8.0 Serving Units=oz Ingredient Name=Spaghetti Noodle

Here's where I call the insert function that is in

public void saveIngredientData() {

        try {
            String ingredient = ingredient_editText.getText().toString();
            String servingUnits = spinner.getSelectedItem().toString();
            double servPerContainer = Double.parseDouble(SPC_editText.getText().toString());

            long id = databaseHelper.insertIngredientData(ingredient, servingUnits, servPerContainer);
            if (id < 0)
                Message.message(this, "Insert was Unsuccessful");
                Message.message(this, "Successfully entered a row");
        } catch (NumberFormatException e) {
            Message.message(getApplicationContext(), ""+e);

And here's the insertIngredientData function that contains a syntax error, located in

public long insertIngredientData(String ingredientName, String units, double spc){
    SQLiteDatabase db = helper.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(DatabaseHelper.INGREDIENT_NAME, ingredientName);
    contentValues.put(DatabaseHelper.SERVING_UNITS, units);
    contentValues.put(DatabaseHelper.SPC, spc);
    long id = db.insert(DatabaseHelper.TABLE_INGREDIENT, null, contentValues);
    return id;


You are using spaces in field names.

You better use underscores (_) instead. I.e.: private static final String SPC = "Servings_Per_Container";.
OR (if you really want to insist using spaces), you must include the field names in brackets ([ and ]). I.e.: private static final String SPC = "[Servings Per Container]";.

Correct ALL your field names, not only the one in the example.


sqlite: How can results be made unique according to a column

Currently, the following sqlite query returns 45 records. I know that only 4 albums exist. How can the query be made to return only those records that are unique to albumTable.album. Pseudo Code: where albumTable.album is UNIQUE query = new StringBuilder(); query.append("select albumTable.album, artistTable.artist, songTable.filepath "); query.append("from albumTable "); query.append("inner...

Create table sqlite syntax error

Caused by: android.database.sqlite.SQLiteException: near "case": syntax error (code 1):, while compiling At CREATE TABLE case ( case_id TEXT PRIMARY KEY, case_body TEXT, case_title TEXT, case_published INTEGER, case_thumbnil TEXT,case_type TEXT ); Can any one please tell me what is the problem, I am testing this on Android 5.0.2 I have...

no such column error - sqlite

I get a strange error: E/SQLiteLog﹕ (1) no such column: Test 06-22 01:51:20.006 15089-15089/com.almas.mehr.sms E/AndroidRuntime﹕ FATAL EXCEPTION: main android.database.sqlite.SQLiteException: no such column: Test (code 1): , while compiling: SELECT * FROM groups WHERE title = Test at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method) at android.database.sqlite.SQLiteConnection.acquirePreparedStatement( at...

python if statement inside for syntax error

I wrote some code but I can't get why the pyscripter is telling a syntax error in the if statement: #search for 9 elements file_writer = open('C:\\PythonProject2\\commands_NUM.txt','w') for item in data_indices: flag= search_object(item,data,obj_value_min,obj_value_max) if flag = True:###ERROR file_writer.write('frame0: ' + str(item[0]+1)+' ' + str(item[1]+1) + '\n') ##Here is the syntax...

syntax error can't pinpoint the bug in javascript

I continue to receive a syntax error and can't figure out why, please help. alert ("CAN YOU BEAT VALERIE AT ROCK PAPER SCISSORS?"); var userChoise = prompt ("Rock, Paper, Scissors"); var computerChoice = Math.random(); if (computerChoice < 0.34) { computerChoice = "rock"; } else if (0.34 >= computerChoice < 0.67)...

syntax error : missing ')' before 'constant'

I have some syntax problems that I don't know how to fix. I'm trying to build some functions to matrix, can someone help me resolve those problems? 1>c:\documents and settings\one\my documents\visual studio 2010\projects\hw3\hw3\q2.c(11): error C2143: syntax error : missing ')' before 'constant' 1>c:\documents and settings\one\my documents\visual studio 2010\projects\hw3\hw3\q2.c(11): error C2143:...

Sending data to rails controller without saving in database

1) I need to get data from the user and process it in one of my controller's function without saving the data from my user in my db. I have this code in my view: <script type="text/javascript"> $(document).ready(function(){ $("#AEI_submit").on('click', function(event) { var aei_login = $("#AEI_login").val(); var aei_password = $("#AEI_mdp").val(); $.ajax({...

Unknown compiling error java

I have been going through some online exercises in Java, and I can't figure out why this tid-bit of code won't compile. I am forgetting something obvious I know it. import java.util.Scanner; class age { public static void main (String[] args) { Scanner keyboard = new Scanner (; int age;...

Android Error implementing CursorAdapter - Column _id

recently that I use sqlite in android and I have a problem not solved. I found a tutorial that explains how to run a database and works perfectly. I'm happy to have found. Now I want to implement a CursorAdapter to customize the listview containing the data of the DB...

IDLE returning syntax errors for no reason that I can discern

# Function starts_with() - Finds if list 1 starts with list 2 : ) def starts_with(list1, list2): count = 0 if length (list1) >= length(list2):(error) for var in range(length(list2):(error) if var == list2[var]: (error) count(error) += 1 else: return false if count = length(list2): return true else: return false This...

re write-sql statement Insert OR REPLACE from java to c++ NDK Android

I need re write this sqlite Statements from java to c++, BEcouse of low performance: I red this arcticle: Improve INSERT-per-second performance of SQLite? But Iam totaly confused, becouse I cant find any sqlstatemenst of Insert or Update public synchronized void saveMatchValue(int photoRecOwner, int[] photoRecAssign, float[] value) { SQLiteDatabase database...

Uncaught SyntaxError: Unexpected token < in HTML - can't solve

Can anyone help me find this unexpected token? I've been looking at this code for a while so maybe i need a fresh pair of eyes to solve this. see HTML code below: <div class="list-view hide"> <table class="custom-reports-table"> <script id="custom-reports-table" type="text/javascript"> <tbody> {{#each listItem}} <tr class="row" id="{{itemId}}"> <td class="select-container"> <div...

Checking, if optional parameter is provided in Dart

I'm new to Dart and just learning the basics. The Dart-Homepage shows following: It turns out that Dart does indeed have a way to ask if an optional parameter was provided when the method was called. Just use the question mark parameter syntax. Here is an example: void alignDingleArm(num axis,...

How to send scheduled SMS messages in Android?

I have to create an app which has some Mobile numbers in its database. It has to send SMS to everyone one of the number in the database at 12:00 AM everyday. I know how to add the numbers in database. But I don't know how to send scheduled messages...

Cant find mySQL request error

Rediculous but I cant find error in this request SELECT * FROM diploms LEFT JOIN student ON diploms.student_id = student.student_id LEFT JOIN group ON student.group_id = group.group_id LEFT JOIN speciality ON group.speciality_id = speciality.speciality_id ORDER BY (CASE WHEN IS NULL THEN 1 ELSE 0 END), ASC But SQL...

Adapter Subscribing to Multiple Observables

My question is What is the best way for an Adapter to subscribe to multiple observables I have an Adapter that has a header and regular item types. The information for the adapter is fed from a database using Sqlbrite. Using Sqlbrite, I want to update the header and the...

Include, Require a syntax error file

I would like to ask can I require/include a file that has syntax errors and if I cant, the require/include returns a value so that I know that the required/included file has syntax errors and cannot be required/included ? file.php has syntax error include('file.php') if (not file.php included because of...

Android SQLite can a tables name be 'TABLE'

I'm using the GreenDAO ORM for SQLite, The problem i'm facing is that I have a table named TABLE, I use the following command to create the table : db.execSQL("CREATE TABLE 'TABLE' (" + // "'_id' INTEGER PRIMARY KEY ," + // 0: id "'TYPE' INTEGER NOT NULL ," +...

Syntax errors when right shift operator is used as a template parameter

If I take the address of a right shift operator and pass it as a template parameter, the right shift symbol is being misread as the end of the template parameter list, and the resulting confusion is causing multiple errors. template <class T, void(T::*)(int)> struct TemplateMagic {}; struct TestStruct {...

SyntaxError: invalid flag after regular expression and white screen

I can't figure out why my page will not work. It just gives me a white screen when I try to load it. Is there a code I am missing? I don't know if my spaces matter either. Here is my code: <!DOCTYPE html> <html> <head><body> <title>Initializing an Array</title> <style...

Is this Android SQL statement vulnerable to SQL injection?

Is the query() method provided by SQLiteDatabase class safe to use without worrying about SQL injections? db.query(TABLE,cols,COL_ID + " = '" + id + "' AND " + COL_FROM + " = '" + from + "'",null,null,null,null); The id and from variables are completely unescaped. Or is the following the...

SQL Server syntax error when joining CTEs

I am using SQL Server 2014 and I am having trouble with my SQL query below. It seems that there is a syntax error somewhere but I just can't find it. I am joining two select queries from two separate views, namely ReservationList and ARACCOUNT. USE MyDatabase ;WITH q1 AS...

Time's Tables Quiz (Error)

HELP NEEDED :D So trying to embark on making a time's tables quiz for my brother.Very new to coding so trying to do it as simple as possible but really stuck. Any help would be awesome Basically I keep getting this error [ In function 'main': Line 17: error: expected...

Error: Expected expression, got end of script

When clicking on the "Print Ticket" button Javascript is throwing an syntax error in firebug indicating "Expected expression, got end of script" However this is a straight forward bit of php/javascript code so i'm at a loss for the syntax problem. This button is not addressed by any Jquery function...

Why does adding parentheses in if condition results in compile error?

The following Go code runs OK: package main import "fmt" func main() { if j := 9; j > 0 { fmt.Println(j) } } But after adding parentheses in condition: package main import "fmt" func main() { if (j := 9; j > 0) { fmt.Println(j) } } There is...

Parse error: syntax error, unexpected '<' PHP [duplicate]

This question already has an answer here: Reference - What does this error mean in PHP? 28 answers I have this code: <p class="test"> <?php $button_value = get_field('button_name'); echo $button_value; if($button_value==1) { <a href="?page_id=26" class="get_quote">get quote</a> } ?> </p> This is the error: Parse error: syntax error, unexpected '<'...

Update Statement with Inline SQL

This syntax keeps giving me an invalid column. All I want to do is insert the value into the table. How should I change my syntax to make it possible? This is the error presented. Msg 207, Level 16, State 1, Line 1 Invalid column name 'Alpha12'. Code: Declare @vector...

MATCH with selectArgs looking like *queryTerm* stopped working on Android 5.0+

This is addendum to my question SQLiteDatabase Cursor empty only on Android 5.0+ devices. That one will be closed as I was not sure what is causing the bug - thought it was a cursor note being properly filled. Now I have discovered what is causing empty cursor. Up to...

How to know what is behind SQLiteCursor's address seen during debugging?

I am debugging an application and when the Cursor retrieves a pointer from the database, I see something like this How can I know what means the value behind @? How can I bind this address to the database value behind it? Why do I need this? The app is...

Cannot reference a field before it is defined, but only if you don't qualify it [duplicate]

This question already has an answer here: Illegal forward Reference java issue 4 answers I found happening with the following code made my jaw drop: public class MCVE { { // instance initializer System.out.println(test); // cannot reference a field before it is defined System.out.println(this.test); } private final String test...

Return One value if more than one Exsist

if i have same values in a column and i want to return only one instead of all of them what would be a method. ArrayList<String> getAllNotes() { Cursor cursor; mDbHelper = mSqliteHelper.getWritableDatabase(); String query = "SELECT * FROM " + SqliteHelpers.TABLE_NAME; cursor = mDbHelper.rawQuery(query, null); ArrayList<String> arrayList = new...

Code academy error (confused) ^^

I would like to know why this code gives the message: SyntaxError: unexpected token else. var compare = function(choice1,choice2){ if(choice1===choice2){ return("The result is a tie!"); }else if(choice1==="rock"){ if(choice2==="scissors"){ return("rock wins"); }else{ return("paper wins"); }else if(choice1==="paper"){ if(choice2==="rock"){ return("paper wins"); } } } };...

Unexpected Symbol in As Formula, Can't Find

I've been using as.formula for setting up a glm, and I can't figure out where the unexpected symbol is. Part of the problem is that the character vector I'm converting is so long. It's about 700 words with + inserted in between in order to turn it into a formula....

Array types are now written with the brackets around the element type

Here's my code (TaskManager.swift): import UIKit var taskMgr: TaskManager = TaskManager () struct task { var name = "untitled" var desc = "none" } class TaskManager: NSObject { var tasks = task[]() func addTask (name: String, desc: String) { tasks.append (task (name: name, desc: desc)) } } then I got...

Getting “Incorrect syntax near”-error with SqlDataReader

I'm getting error and I don't know what's wrong with the code, so If anyone can help me I would be grateful. Error: Incorrect syntax near ','. and the highlighted line is rdr = cmd.ExecuteReader(); Code: cn.Open(); string query = "SELECT * FROM dbo.ispiti WHERE [email protected], [email protected], [email protected]"; SqlCommand cmd...

No such table found even though app successfully opens database from assets folder

I'm new to android development. I'm trying to use a pre-populated database whoch is stored in my assets folder. Log shows that the database gets opened but 'NO SUCH TABLE ERROR' is shown.I can't find any solution to this error. Please help. : package; import android.content.Context; import android.database.Cursor;...

Android SQLite issue: 'Table […] has no column named' error

I keep getting error that a column in my table cannot be found. Cannot figure out why this is happening. The column names appear to be spelled correctly. I'm getting this error : 06-11 21:27:02.701 3703-3703/com.example.luca.contatti E/SQLiteLog﹕ (1) table Contatti has no column named imageUri This is my DatabaseHandler page:...

Unable to display sqllite data into Table Layout

I am new to Android. I'm trying to display the data in a tabular form, loading data from thedatabase`. But it is showing the following error: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it. at android.database.CursorWindow.nativeGetString(Native Method)...

error CS1729: The type `ARSoft.Tools.Net.Dns.DnsServer' does not contain a constructor that takes `4' arguments

I'm trying to compile a code taken from github. My understanding of Visual Studio or C# is pretty basic. Can anybody please help me with the error? Github source: Source file link: Error screenshot: Thanks...

subtracting from multiple variables at a time

So recently I've ben interested in learning python, and I got the "Think python" last Christmas. Unfortunately I haven't had the time to really get into it because of my exams. Even though I the book was written for python 2 I decided to use python 3.4.3 anyway. This does...

select data according to Row in Sqlite

image i want to get the whole row i am using this code to get my desired data but its giving me null pointer exception at temp_address1 here is the code as in mentioned image i want to get the whole row matching phone number. how can i achive that...

Plone - Syntax Error when doing hello world tutorial

I am following this "hello world" tutorial on But I stuck in one moment due to error: [email protected]:~/Plone/python_dev/env-27# cd hello_world [email protected]:~/Plone/python_dev/env-27/hello_world# ../bin/python Traceback (most recent call last): File "", line 70, in <module> exec urllib2.urlopen(setup_url).read() in ez File "<string>", line 1 <!DOCTYPE html> ^ SyntaxError: invalid syntax I...

can anyone tell me how to store geocoder address in android database using android studio?

I am able to see the address(for on click listener) fetching from the GeoCoder code and i am able to display in log file but i am not able to store that address in my local DataBase. can any one please help me in this issue. thanks in advance. package...

Android Studio Create Database error (android.database.sqlite.SQLiteException: near “and”: syntax error (code 1): ) Detailed Analysis

I'm trying to use the database and it complains about my "CREATE TABLE". I looked at different posts and "updated mine on here for the changes I made to CREATE TABLE). It looks correct compared to other posts and forums, so I am not quite sure why it keeps failing....

int android.database.Cursor.getCount()' on a null object reference

got null poiner exception at cursor.getCount(); while doing ListView using cursor loader adapter class as below public class FriendsListCursorAdapter extends CursorAdapter { private Cursor cursor; final VROPreferenceManager preferenceManager = new VROPreferenceManager(); Context con; public FriendsListCursorAdapter(Context context, Cursor c, boolean b) { super(context,c,true); cursor = c; con=context; } public void addItems(Cursor...

Bison:syntax error at the end of parsing

Hello this is my bison grammar file for a mini-programming language: %{ #include <stdlib.h> #include <stdio.h> #include <math.h> #include "" void yyerror(char const *); extern FILE *yyin; extern FILE *yyout; extern int yylval; extern int yyparse(void); extern int n; int errNum = 0; int forNum = 0; %} %left PLUS...

Stored Procedure for insert

I am taking a datatable as parameter in my stored procedure and I am trying to insert a few of its column in one of the database tables but I don't know the correct syntax. This is what I have tried ALTER PROCEDURE [dbo].[spInsertInvoice] @tblInvoice [TypeExcel] READONLY AS BEGIN SET...

Passing parameter in Sql IN statement

How can I pass a parameter in the IN SQL statement ? cursor = readableDb.rawQuery("SELECT * FROM User where User.objectId NOT IN (@Par)", new String{"ID"} ); Is it the correct way to do it ?...

SQLiteDatabase Cursor empty only on Android 5.0+ devices

The application has a SearchView which fetches suggestions from a specific database table. Everything worked without any errors until Android 5.0 appeared. As of then, when the SQLiteQueryBuilder queries the database to fill the Cursor object, the return is empty cursor. Not NULL, but empty. On other platforms, I can...

Getting ordered subset of records

I have table which basically describes a bus route. The table includes all the stops of a particular route. This SQLFiddle shows an example. The data shows the flow in one direction, but a route can also be in the other direction. I need to get a subset of this...