SQLite create table - java

Im unable to create SQLite table.
Android Studio IDE shows me error on this line "Column constrains or Comma expected, got Text"
String CREATE_TABLE_CONTACTS = "CREATE TABLE " + Util.TABLE_NAME + "(" +
Util.KEY_ID + " INTEGER PRIMARY KEY," + Util.KEY_NAME + " TEXT," +
Util.KEY_PHONE_NUMBER + " TEXT" + ")";

IMO your code
String CREATE_TABLE_CONTACTS = "CREATE TABLE " + Util.TABLE_NAME + "(" +
Util.KEY_ID + " INTEGER PRIMARY KEY," + Util.KEY_NAME + " TEXT," +
Util.KEY_PHONE_NUMBER + " TEXT" + ")";
is ok problems belongs from Util.TABLE_NAME or Util.KEY_ID check here these key strings not having spaces
DO => user_name
DON'T => user name

If your columns happen to have whitespace or other reserved words, then you may try escaping them using double quotes:
String CREATE_TABLE_CONTACTS = "CREATE TABLE \"" + Util.TABLE_NAME + "\" (" +
"\"" + Util.KEY_ID + "\" INTEGER PRIMARY KEY, \"" + Util.KEY_NAME + "\" TEXT, \"" +
Util.KEY_PHONE_NUMBER + "\" TEXT" + ")";

private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "addToCart_db";
public static final String TABLE_NAME = "addToCart";
public static final String COLUMN_ID = "id";
public static final String COLUMN_PRODUCT_ID = "product_id";
public static final String COLUMN_QTY = "qty";
public static final String COLUMN_PRICE = "price";
public static final String CREATE_TABLE =
"CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_PRODUCT_ID + " TEXT,"
+ COLUMN_PRICE + " TEXT,"
+COLUMN_QTY +" TEXT)";
try it, this formatting create table

Related

android.database.sqlite.SQLiteException: near ")": syntax error (code 1): [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am trying to create a table in DB, but I am getting SQLite exception.I have tried almost everything to fix it, but of no use.I dont know why am I getting this error. Removing comma at the end gives another exception : android.database.sqlite.SQLiteException: table products has no column named _cost (code 1):
Any suggestion is welcome.
how do I fix it ?
This is my DB handler class :
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 4;
private static final String DATABASE_NAME= "products.db";
private static final String TABLE_PRODUCTS = "products";
private static final String COLUMN_ID = "_id";
private static final String COLUMN_PRODUCTNAME = "productname";
private static final String COLUMN_VENUE = "venue";
private static final String COLUMN_DATEOFSTART = "_dateofstart";
private static final String COLUMN_DATEOFEND = "_dateofend";
private static final String DURATION_WORKSHOP= "_duration";
private static final String COST_WORKSHOP = "_cost";
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context,DATABASE_NAME, factory,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_PRODUCTS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_PRODUCTNAME + " TEXT, " +
COLUMN_VENUE + " TEXT, " +
COLUMN_DATEOFSTART + " TEXT, " +
COLUMN_DATEOFEND + " TEXT, " +
DURATION_WORKSHOP + "INTEGER, " +
COST_WORKSHOP + "INTEGER, " +
");" ;
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
onCreate(db);
}
public void addProduct (Products products){
ContentValues values = new ContentValues();
values.put(COLUMN_PRODUCTNAME,products.get_productname());
values.put(COLUMN_VENUE,products.get_venue());
values.put(COLUMN_DATEOFSTART,products.get_dateofstart());
values.put(COLUMN_DATEOFEND,products.get_dateofend());
values.put(DURATION_WORKSHOP,products.get_duration());
values.put(COST_WORKSHOP,products.get_cost());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_PRODUCTS,null,values);
db.close();
}
LOGCAT :
Caused by: android.database.sqlite.SQLiteException: near ")": syntax error (code 1): , while compiling: CREATE TABLE products(_id INTEGER PRIMARY KEY AUTOINCREMENT, productname TEXT, venue TEXT, _dateofstart TEXT, _dateofend TEXT, _durationINTEGER, _costINTEGER, );
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:1675)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1606)
at com.example.dell_1.sqlite.MyDBHandler.onCreate(MyDBHandler.java:38)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at com.example.dell_1.sqlite.MyDBHandler.addProduct(MyDBHandler.java:57)
at com.example.dell_1.sqlite.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:6705)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
Line 38 is db.execSQL(query); and line 57 is SQLiteDatabase db = getWritableDatabase();
change your query to this , you're missing some spaces and also you must remove the last comma from the query
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_PRODUCTS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_PRODUCTNAME + " TEXT, " +
COLUMN_VENUE + " TEXT, " +
COLUMN_DATEOFSTART + " TEXT, " +
COLUMN_DATEOFEND + " TEXT, " +
DURATION_WORKSHOP + " INTEGER, " +
COST_WORKSHOP + " INTEGER " +
");" ;
db.execSQL(query);
}
replace your query with this
String query = "CREATE TABLE " + TABLE_PRODUCTS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_PRODUCTNAME + " TEXT, " +
COLUMN_VENUE + " TEXT, " +
COLUMN_DATEOFSTART + " TEXT, " +
COLUMN_DATEOFEND + " TEXT, " +
DURATION_WORKSHOP + "INTEGER, " +
COST_WORKSHOP + "INTEGER " +
");" ;
actually you are putting one extra , at the end of query.
Change your query to this
String query = "CREATE TABLE " + TABLE_PRODUCTS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_PRODUCTNAME + " TEXT, " +
COLUMN_VENUE + " TEXT, " +
COLUMN_DATEOFSTART + " TEXT, " +
COLUMN_DATEOFEND + " TEXT, " +
DURATION_WORKSHOP + " INTEGER, " +
COST_WORKSHOP + " INTEGER " +
");" ;
You have formatting errors in there. An extra comma and two column names concatenated with their column types. See for e.g. how _costINTEGER should be _cost INTEGER
Change AUTOINCREMENT to AUTO_INCREMENT and remove extra ',' after column COST_WORKSHOP
String query = "CREATE TABLE " + TABLE_PRODUCTS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTO_INCREMENT, " +
COLUMN_PRODUCTNAME + " TEXT, " +
COLUMN_VENUE + " TEXT, " +
COLUMN_DATEOFSTART + " TEXT, " +
COLUMN_DATEOFEND + " TEXT, " +
DURATION_WORKSHOP + " INTEGER, " +
COST_WORKSHOP + " INTEGER " +
");" ;

Error while inserting data in sqlite db in android [duplicate]

i'm still learning Android development, And i have a problem creating an sqlite database table. here is a part of my code :
`
private static final String CREATE_ADS_PICTURE = "CREATE TABLE "
+ AdsBDD.TABLE_ADS_PICTURE + "(" + AdsBDD.ID_PICS
+ " INTEGER PRIMARY KEY AUTOINCREMENT ," + AdsBDD.AD_ID
+ " INTEGER NOT NULL," + AdsBDD.PICTURE + " TEXT," + AdsBDD.FOLDER
+ " TEXT," + AdsBDD.ORDER_NO + " INTEGER NOT NULL);";
private static final String CREATE_AGENCES = "CREATE TABLE "
+ AgencesBDD.TABLE_AGENCES + "(" + AgencesBDD.ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + AgencesBDD.GROUP
+ " INTEGER," + AgencesBDD.USERNAME + " TEXT," + AgencesBDD.EMAIL
+ " TEXT," + AgencesBDD.CONTACT_NAME + " TEXT,"
+ AgencesBDD.REGISTRATION_DATE + " TEXT," + AgencesBDD.ACTIVATION
+ " TEXT," + AgencesBDD.ACTIVE + " INTEGER," + AgencesBDD.STORE
+ " INTEGER," + AgencesBDD.STORE_BANNER + " TEXT,"
+ AgencesBDD.RATING + " REAL," + AgencesBDD.LANGUAGE + " TEXT,"
+ AgencesBDD.IDENTITY + " TEXT," + AgencesBDD.ADDRESS + " TEXT,"
+ AgencesBDD.PHONE + " TEXT," + AgencesBDD.COMPANY + " TEXT,"
+ AgencesBDD.WEBPAGE + " TEXT," + AgencesBDD.CODE_POSTAL + " TEXT,"
+ AgencesBDD.JE_SUIS_UN + " TEXT," + AgencesBDD.VILLE + " TEXT,"
+ AgencesBDD.VIDEO + " TEXT);";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_ADS_PICTURE);
db.execSQL(CREATE_AGENCES);
}
public class AgencesBDD {
public static final String TABLE_AGENCES = "agences";
public static final String ID = "id";
public static final String GROUP = "group";
public static final String USERNAME = "username";
public static final String EMAIL = "email";
public static final String CONTACT_NAME = "contact_name";
public static final String REGISTRATION_DATE = "registration_date";
public static final String ACTIVATION = "activation";
public static final String ACTIVE = "active";
public static final String STORE = "store";
public static final String STORE_BANNER = "store_banner";
public static final String RATING = "rating";
public static final String LANGUAGE = "language";
public static final String IDENTITY = "identity";
public static final String ADDRESS = "address";
public static final String PHONE = "phone";
public static final String COMPANY = "company";
public static final String WEBPAGE = "webpage";
public static final String CODE_POSTAL = "code_postal";
public static final String JE_SUIS_UN = "je_suis_un";
public static final String VILLE = "ville";
public static final String VIDEO = "video";
`
So the problem is that Sqlite throws this exception for the table AGENCES, but the Table AD_PICTURE works fine:
03-08 14:36:01.892: E/AndroidRuntime(10822): FATAL EXCEPTION: main
03-08 14:36:01.892: E/AndroidRuntime(10822): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.infonetdiffusion.immohabitation/com.infonetdiffusion.immohabitation.FragmentBaseActivity}: android.database.sqlite.SQLiteException: near "group": syntax error (code 1): , while compiling: CREATE TABLE agences(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,group INTEGER,username TEXT,email TEXT,contact_name TEXT,registration_date TEXT,activation TEXT,active INTEGER,store INTEGER,store_banner TEXT,rating REAL,language TEXT,identity TEXT,address TEXT,phone TEXT,company TEXT,webpage TEXT,code_postal TEXT,je_suis_un TEXT,ville TEXT,video TEXT);
it should be easy to fix, but i can't find where i'm wrong...
any help would be apreciated!
you are using sqlite keyword as column name i.e. group sqliteKeyword which is restrict
Drop the NOT NULL for the id column.
Read here
Those two cases are not equivalent! Note that primary key in first case doesn't have NOT NULL.
CREATE TABLE agences(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,group INTEGER,username TEXT,email TEXT,contact_name TEXT,registration_date TEXT,activation TEXT,active INTEGER,store INTEGER,store_banner TEXT,rating REAL,language TEXT,identity TEXT,address TEXT,phone TEXT,company TEXT,webpage TEXT,code_postal TEXT,je_suis_un TEXT,ville TEXT,video TEXT);
group is a key word in sql, you can't use it as a column name, change group to other strings that can't be key word in sql

Problems when INSERT into DB

When I try to submit data into the database, the app crashes.
Here are the parts of the java file concerned with creating and inserting data into the database.
My Contract.java class has the following information:
public class Contract {
public static abstract class customReminder{
public static final String TABLE_NAME = "CUSTOM_REMINDER";
public static final String ID = "ID";
public static final String TITLE = "TITLE";
public static final String DESCRIPTION = "DESCRIPTION";
public static final String DATE_TIME = "DATE_TIME";
public static final String[] REMINDER_COLUMNS = {ID, TITLE, DESCRIPTION, DATE_TIME};
}
My DBHelper.java class:
//SQLite statement for custom reminder table
public static final String CUSTOM_REMINDER_TABLE = "CREATE TABLE " + Contract.customReminder.TABLE_NAME + "("
+ Contract.customReminder.ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Contract.customReminder.TITLE + " TEXT,"
+ Contract.customReminder.DESCRIPTION + " TEXT,"
+ Contract.customReminder.DATE_TIME + " TEXT,"
+ ");";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CUSTOM_REMINDER_TABLE);
}
My CustumRemider.java class:
public boolean createCustomReminder(String title, String description, String dateTime){
ContentValues contentValues = new ContentValues();
contentValues.put(mAllColumns[1], title);
contentValues.put(mAllColumns[2], description);
contentValues.put(mAllColumns[3], dateTime);
long result = mDatabase.insert(Contract.customReminder.TABLE_NAME, null, contentValues);
return result != -1;
}
I downloaded the database to my PC from Android Device Monitor and opened it with SQLiteBrowser. I notice that a table android_metadata is created instead of CUSTOM_REMINDER.
CREATE TABLE android_metadata (locale TEXT)
I neither know where the query comes from nor why it does this.
You need to change
delete comma (",") after last parameter in create table query
public static final String CUSTOM_REMINDER_TABLE = "CREATE TABLE " + Contract.customReminder.TABLE_NAME + "("
+ Contract.customReminder.ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Contract.customReminder.TITLE + " TEXT,"
+ Contract.customReminder.DESCRIPTION + " TEXT,"
+ Contract.customReminder.DATE_TIME + " TEXT"
+ ");";
instead of this
public static final String CUSTOM_REMINDER_TABLE = "CREATE TABLE " + Contract.customReminder.TABLE_NAME + "("
+ Contract.customReminder.ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Contract.customReminder.TITLE + " TEXT,"
+ Contract.customReminder.DESCRIPTION + " TEXT,"
+ Contract.customReminder.DATE_TIME + " TEXT,"
+ ");";

SQLite exception near ") "

I am getting error like "SQLite exception near ") ":syntax error (code 1)
here is my create table command
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "attendance.db";
private static final String TEXT_TYPE = " TEXT";
private static final String COMMA_SEP = " ,";
private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " +
TableElement.TABLE_NAME + " (" +
TableElement.ID_COLUM + " INTEGER PRIMARY KEY AUTOINCREMENT ," +
TableElement.IMAGE_COLUM + TEXT_TYPE + COMMA_SEP +
TableElement.NAME_COLUM + TEXT_TYPE + COMMA_SEP +
TableElement.GARDIAN_NAME_COLUM + TEXT_TYPE + COMMA_SEP +
TableElement.CONTRACT_COLUM + TEXT_TYPE + COMMA_SEP +
TableElement.PRESENT_COLUM + TEXT_TYPE + COMMA_SEP +
TableElement.ABSENT_COLUM + TEXT_TYPE + COMMA_SEP +
TableElement.LATE_COLUM + TEXT_TYPE + COMMA_SEP +
TableElement.CHECKED_BUTTON_COLUM + TEXT_TYPE + COMMA_SEP +
" )";
You do not need the last COMMA_SEP.
When in doubt, print the SQL query out and these syntax errors become more visible. In this instance, the ) in the error message suggests the error is close to the end.
Other thoughts:
Some of these static variables, eg. COMMA_SEP, are making your code harder to read.
You have mis-spelt COLUMN on your column name attributes.

SQLite insert into error (Android)

Error
12-22 14:30:52.329 1261-1261/com.TrackApp.trackapp E/SQLiteLog﹕ (1) near "Throw": syntax error
12-22 14:30:52.329 1261-1261/com.TrackApp.trackapp D/AndroidRuntime﹕ Shutting down VM
12-22 14:30:52.339 1261-1261/com.TrackApp.trackapp W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40a13300)
12-22 14:30:52.389 1261-1261/com.TrackApp.trackapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.database.sqlite.SQLiteException: near "Throw": syntax error (code 1): , while compiling: INSERT INTO Athletes (ID, First_Name, Last_Name, Age, Gender, Event, Tier) VALUES (0, Joe, Richards, 20, Male, Discus Throw, 2);
I keep getting this error when trying to add a new athlete to my database. Could someone please figure out what I am doing wrong. I am almost certain all of my sql statements are correct. I think it thinks that it is creating a new column under events for whatever is from the athlete object but I don't know
private static final String DATABASE_NAME = "AthletesDB";
private static final int VERSION = 1;
private static final String TABLE_NAME = "Athletes";
private static final String COLUMN_ID = "ID";
private static final String COLUMN_FIRST_NAME = "First_Name";
private static final String COLUMN_LAST_NAME = "Last_Name";
private static final String COLUMN_AGE = "Age";
private static final String COLUMN_GENDER = "Gender";
private static final String COLUMN_EVENT = "Event";
private static final String COLUMN_TIER = "Tier";
private static final String[] COLUMNS = {"ID", "First_Name", "Last_Name", "Age", "Gender", "Event", "Tier"};
private static final String TABLE_CREATE = "CREATE TABLE " + TABLE_NAME + "( " + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_FIRST_NAME + " VARCHAR(20), " + COLUMN_LAST_NAME + " VARCHAR(20), " + COLUMN_AGE + " INTEGER, " +
COLUMN_GENDER + " VARCHAR(20), " + COLUMN_EVENT + " VARCHAR(20), " + COLUMN_TIER + " INTEGER " + ")";
public MySQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CREATE);
onCreate(db);
}
public void addAthlete(Athlete athlete){
SQLiteDatabase db = this.getWritableDatabase();
/*ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_ID, athlete.getID());
contentValues.put(COLUMN_FIRST_NAME, athlete.getFirstName());
contentValues.put(COLUMN_LAST_NAME, athlete.getLastName());
contentValues.put(COLUMN_AGE, athlete.getAge());
contentValues.put(COLUMN_GENDER, athlete.getGender());
contentValues.put(COLUMN_EVENT, athlete.getEvent());
contentValues.put(COLUMN_TIER, athlete.getTier());*/
// db.insert(TABLE_NAME, null, contentValues);
db.execSQL("INSERT INTO " + TABLE_NAME + " (" + COLUMN_ID + ", " + COLUMN_FIRST_NAME + ", " + COLUMN_LAST_NAME
+ ", " + COLUMN_AGE + ", " + COLUMN_GENDER + ", " + COLUMN_EVENT + ", " + COLUMN_TIER + ")" +
" VALUES " + "(" + athlete.getID() + ", " + athlete.getFirstName()
+ ", " + athlete.getLastName() + ", " + athlete.getAge() + ", " + athlete.getGender() + ", " +
athlete.getEvent() + ", " + athlete.getTier() + ");");
db.close();
}
You should surround the string values you insert with single quotes. The exception is thrown because you have whitespace in your literal "Discus Throw". Try the following:
db.execSQL("INSERT INTO "
+ TABLE_NAME + " ("
+ COLUMN_ID + ", "
+ COLUMN_FIRST_NAME + ", "
+ COLUMN_LAST_NAME + ", "
+ COLUMN_AGE + ", "
+ COLUMN_GENDER + ", "
+ COLUMN_EVENT + ", "
+ COLUMN_TIER + ")" +
" VALUES " + "("
+ athlete.getID() + ", "
+ athlete.getFirstName() + ", "
+ athlete.getLastName() + ", "
+ athlete.getAge() + ", "
+ athlete.getGender() + ", "
+ "'" + athlete.getEvent() + "'" + ", "
+ athlete.getTier() + ");");
which gives you
INSERT INTO Athletes (ID, First_Name, Last_Name, Age, Gender, Event, Tier)
VALUES (0, Joe, Richards, 20, Male, 'Discus Throw', 2);
Surround each entry of type TEXT in VALUES with single quotes.
For example,
" VALUES ('" + athlete.getFirstName() + "')"
Or, written out:
" VALUES ('Bob')"

Categories