I'm trying to create a table in android database, but when i try to run the application the LogCat returns the following error:
08-22 02:39:29.098: ERROR/AndroidRuntime(277): Caused by: android.database.sqlite.SQLiteException: near "auto_increment": syntax error: CREATE TABLE words(id INTEGER PRIMARY KEY, word TEXT, count INTEGER not null auto_increment)
The code for this error is this:
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY, word TEXT, count INTEGER not null auto_increment)");
}
And there is a error on this line too, the one between arrows:
public DataHelper(Context context) {
this.context = context;
OpenHelper openHelper = new OpenHelper(this.context);
-->this.db = openHelper.getWritableDatabase();<--
this.insertStmt = this.db.compileStatement(INSERT);
this.updateStmt = this.db.compileStatement(UPDATE);
}
Ps: The codes before is from DataHelper class.
and erro at this line (the logcat just say the line of the class, dont say the error):
this.dh = new DataHelper(this);
Ps: DataHelper is the class that manage the database.
Change auto_increment to autoincrement and you should be good. Simple syntax error :)
There are two problems in count INTEGER not null auto_increment
as mentioned by smith324, auto_increment is spelled wrong
more importantly, count has to be primary key, if you want to have it auto-increment by sqlite rules.
Related
Hi in my senario there is a table with 4 columns and im trying to create another table with connection to the first table but i dont whay im getting this error in logcat
2019-10-28 01:04:00.853 29812-29812/com.test.fastfoodfinder E/SQLiteDatabase: Error inserting notes_main=testeststststststststs
android.database.sqlite.SQLiteException: no such table: notes (code 1 SQLITE_ERROR): , while compiling: INSERT INTO notes(notes_main) VALUES (?)
so i have created a class for my data base and this is what i have done
public class RestaurantDBHelper extends SQLiteOpenHelper {
private final static String DATABASE_NAME = "FastFood_DataBase.db";
private final static int DATABASE_VERSION = 1;
private final static String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME +
"(" + COLUMN_RESTAURANT_ID + " INTEGER PRIMARY KEY ," +
COLUMN_RESTAURANT_NAME + " TEXT, " +
COLUMN_RESTAURANT_ADDRESS + " TEXT, " +
COLUMN_RESTAURANT_TYPE + " INTEGER, " +
COLUMN_RESTAURANT_IMAGE + " INTEGER);";
private final static String CREATE_TABLE_NOTES = "CREATE TABLE " + TABLE_NAME_NOTES +
"(" + COLUMN_NOTES_ID + " INTEGER PRIMARY KEY, "
+ COLUMN_NOTES + " TEXT," + "FOREIGN KEY (" + COLUMN_NOTES_ID + ") REFERENCES " + TABLE_NAME +"(restaurant_id) ON DELETE CASCADE)";
public final static String DELETE_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;
public RestaurantDBHelper(#Nullable Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("PRAGMA FOREIGN_KEYS = ON;");
db.execSQL(CREATE_TABLE);
db.execSQL(CREATE_TABLE_NOTES);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DELETE_TABLE);
onCreate(db);
}
public void addRestaurant(Restaurant restaurant) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_RESTAURANT_NAME, restaurant.getName());
values.put(COLUMN_RESTAURANT_ADDRESS, restaurant.getAddress());
values.put(COLUMN_RESTAURANT_TYPE,restaurant.getType());
values.put(COLUMN_RESTAURANT_IMAGE, restaurant.getType());
db.insert(TABLE_NAME, null, values);
db.close();
}
public void addNotes (Restaurant restaurant) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NOTES,restaurant.getNote());
db.insert(TABLE_NAME_NOTES,null,values);
db.close();
}
and
public class RestaurantContract {
public static class EntryRestaurants {
public final static String TABLE_NAME = "restaurants";
public final static String COLUMN_RESTAURANT_ID = "restaurant_id";
public final static String COLUMN_RESTAURANT_NAME = "restaurant_name";
public final static String COLUMN_RESTAURANT_ADDRESS = "restaurant_address";
public final static String COLUMN_RESTAURANT_TYPE = "restaurant_type";
public final static String COLUMN_RESTAURANT_IMAGE = "restaurant_image_type";
public final static String COLUMN_RESTAURANT_NOTE_ID = "note_id";
public final static String TABLE_NAME_NOTES = "notes";
public final static String COLUMN_NOTES_ID = "notes_id";
public final static String COLUMN_NOTES = "notes_main";
public final static int RESTAURANT_TYPE_DELIVERY = 1;
public final static int RESTAURANT_TYPE_SITDOWN = 2;
public final static int RESTAURANT_TYPE_TAKEAWAY = 3;
}
}
im kind a new in android so any help would be appreciated,thanks
I believe that your issue is with the onCreate method. This ONLY runs when the database is created, it does not run every time the App is run.
The easiest solution, assuming that you do not need to keep any existing data, is to either delete the App's data or to uninstall the App. After doing either rerun the App and the new table will be created as the onCreate method will then run.
Furthermore it is no use turning FOREIGN KEYS on in the onCreate method. FOREIGN KEYS need to be turned on every time the App is run. To fix this, override the onConfigure method and then use db.setForeignKeyConstraintsEnabled(true);
this is just a convenient alternative to using db.execSQL("PRAGMA FOREIGN_KEYS = ON;");, so if you prefer you could use this when overriding the onConfigure method.
e.g. add this method to the RestaurantDBHelper class :-
#Override
public void onConfigure(SQLiteDatabase db) {
super.onConfigure(db);
db.setForeignKeyConstraintsEnabled(true);
}
However, you will then have issues when trying to add notes as the child will be set to null and thus their will not be a link/map/association/reference between the added note and the restaurant.
You need to use something like :-
public long addNote(String note, long restaurantId) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NOTES,note);
values.put(COLUMN_NOTES_ID,restaurantId);
return db.insert(TABLE_NAME_NOTES,null,values);
}
BUT then you may then have an issue as to determining the id of the restaurant.
BUT then you may then encounter a further issue in that you could only have one note per restaurant as the column used to reference the restaurant is defined as INTEGER PRIMARY KEY and is therefore is a UNIQUE column (the same value can only be used once (an exception is null as a null is considered to be unique to another null)).
If the requirement is for one note per restaurant then there is no need for the separate table the relationship is a one to one relationship so the value can be stored in the restaurant table.
If you want a restaurant to have multiple notes (one to many relationship) then you should not make the column INTEGER PRIMARY KEY, INTEGER would suffice. Then a number of notes could reference the same restaurant.
If you wanted a note to be able to be be applied to a number of restaurants then you'd use a third mapping/line/reference/associative table (other name probably also exist). Such a table would have two columns one to reference the restaurant and the other to reference the note. You would then have a many to many relationship between restaurants and notes (a note could be used by many restaurants and a restaurant could use many notes).
You may find The 3 Types of Relationships in Database Design helpful.
You have enabled foreign key constraints and thus must have a unique primary key for the foreign key to reference.
https://sqlite.org/foreignkeys.html#fk_indexes
says
If the database schema contains foreign key errors that require looking at more than one table definition to identify, then those errors are not detected when the tables are created. Instead, such errors prevent the application from preparing SQL statements that modify the content of the child or parent tables in ways that use the foreign keys. Errors reported when content is changed are "DML errors" and errors reported when the schema is changed are "DDL errors". So, in other words, misconfigured foreign key constraints that require looking at both the child and parent are DML errors. The English language error message for foreign key DML errors is usually "foreign key mismatch" but can also be "no such table" if the parent table does not exist. Foreign key DML errors are reported if:
The parent table does not exist, or
The parent key columns named in the foreign key constraint do not exist, or
The parent key columns named in the foreign key constraint are not the primary key of the parent table and are not subject to a unique constraint using collating sequence specified in the CREATE TABLE, or
The child table references the primary key of the parent without specifying the primary key columns and the number of primary key columns in the parent do not match the number of child key columns.
Given that you never give the restaurant_id a value when you inserting a restaurant then the primary key of the restaurants is probably always null and thus not unique
(Yes according to https://www.sqlitetutorial.net/sqlite-primary-key/ to make the current version of SQLite compatible with the earlier version, SQLite allows the primary key column to contain NULL values. )
So I would say the solution is to create restaurant entries with a unique primary key value when you insert a restaurant or get the database to generate a unique value creating the the restaurant table with the line:-
private final static String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME +
"(" + COLUMN_RESTAURANT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
....
One way to confirm this is download FastFood_DataBase.* files using Device Explorer in your app's database directory and then open it up in https://sqlitebrowser.org/ on your computer to confirm the contents.
I have an app using SQLiteAssetHelper. I'm trying to update its database to include an additional table.
All is well except I cannot make the primary key to autoincrement. Whatever I try gives me an exception.
I reckon it could be a syntax issue since using INTEGER instead of INT also crashes the app.
Where can I find a reference for the syntax that SQLiteAssetHelper uses?
Thank you all.
The offending script looks as follows:
CREATE TABLE heat (
_id int PRIMARY KEY AUTOINCREMENT,
amount int,
comment text
);
Even when I get the script to work (is it AUTOINCREMENT or auto_increment?), insert statements fail to add a value in the _id column. It is left blank.
final ContentValues cv = new ContentValues();
cv.put( KEY_AMOUNT, lAmount );
cv.put( KEY_COMMENT, sComment );
final long lId = m_db.insert( TABLE_NAME, null, cv );
Change the database version to upgrade the table
private static final int DATABASE_VERSION = 1;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
AUTOINCREMENT requires an INTEGER PRIMARY KEY, an INT PRIMARY KEY won't do. Changing that fixed the problem with the SQL you posted. If you have other problems, please post the exception message and code that causes it.
I'm trying to create two tables in my android app database and the application crashes when i'm tring to insert values to the first table, but when i delete the database and recreate it only with one table, it works fine. i don't get it?
the code is:
private static String query_create_user = "CREATE TABLE User ( email TEXT PRIMARY KEY, firstName TEXT, lastName TEXT, password TEXT)";
private static String query_create_group = "CREATE TABLE Group ( groupNumber INTEGER PRIMARY KEY AUTOINCREMENT, courseNumber INTEGER, groupName TEXT, groupType TEXT, groupOwner TEXT)";
public SchoolBagDataBase (Context applicationcontext) {
super(applicationcontext, "contract.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(query_create_user);
database.execSQL(query_create_group);
}
thanks in advance!
The SQL statement held in string 'query_create_group' is invalid. You can't have a table called Group because GROUP is a reserved word in SQLite. Just choose a different name for your table.
I have the next code to create my db..
public class ModeloPaciente extends SQLiteOpenHelper {
//Tabla Proposicion Condicional
static final String proposicionCondicionalTabla="ProposicionCondicional";
static final String colproposicionCondicionalID="ProposicionCondicionalID";
static final String colproposicionCondicionalDescripcion="ProposicionCondicionalDescripcion";
static final String colproposicionCondicionalcuandoInferirForeign="CuandoInferir";
public ModeloPaciente(Context context) {
super(context, dbName, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+proposicionCondicionalTabla+" " +
"("+colproposicionCondicionalID+ " INTEGER PRIMARY KEY AUTOINCREMENT, " +
colproposicionCondicionalDescripcion+ " TEXT NOT NULL," +
colproposicionCondicionalcuandoInferirForeign+" INTEGER NOT NULL,"+
"FOREIGN KEY ("+colproposicionCondicionalcuandoInferirForeign+") REFERENCES "+cuandoInferirTabla+"
("+colcuandoInferirID+"));");
}
Later I put data inside the table like this
public boolean insertarProposicion(Proposicion proposicion) {
try {
SQLiteDatabase db=this.getWritableDatabase();
ContentValues cv= new ContentValues();
cv.put(colproposicionCondicionalDescripcion, proposicion.getProposicionCondicionalDescripcion());
cv.put(colproposicionCondicionalcuandoInferirForeign, getCuandoInferirID(proposicion.getProposicionCondicionalCuandoInferirForeign()));
db.insert(proposicionCondicionalTabla, colproposicionCondicionalID, cv);
//db.close();
return true;
} catch (Exception e) {
System.out.println(e);
return false;
}
But I get an error that said:
06-07 15:36:15.507: E/Database(257): Error inserting CuandoInferir=1 ProposicionCondicionalDescripcion=Se debe inferir acerca de los dias de marcha realizados o no
06-07 15:36:15.507: E/Database(257): android.database.sqlite.SQLiteException: no such column: CuandoInferir: , while compiling: INSERT INTO ProposicionCondicional(CuandoInferir, ProposicionCondicionalDescripcion) VALUES(?, ?);
And I check the database and it has the corresponding column "CuandoInferir"..¿What happen, I do not know? Thanks for your help
You might be working with an older version of the database. Clear your app's data and try again:
Settings --> Applications --> Manage applications --> [your app] --> Clear data
Your code seems fine, however I would check the existing database. Check the column names in the 'ProposicionCondicional' table. You can do it by opening your database in sqlite3 following these steps (obviously connect your phone to pc before doing the steps)
adb shell
cd /data/data/<your.applications.package>/databases
sqlite3 <databases_name>
.schema
See if the table really has the 'CuandoInferir' column. If not, try to recreate the table.
I'm creating a dataBase to insert a *unique patient *(no more than one), so I just created a database that doesn't autoincrement its id like this:
CREATE TABLE IF NOT EXISTS PACIENTE(idPaciente INTEGER PRIMARY KEY, nombre VARCHAR(100) NOT NULL, apellidos VARCHAR(100), email VARCHAR(100), genero CHAR, edad INTEGER NOT NULL, peso INTEGER, kMedico INTEGER, pkHistorial INTEGER, pkConfProg INTEGER, altura INTEGER, FOREIGN KEY (pkMedico) REFERENCES MEDICO(idMedico), FOREIGN KEY (pkHistorial) REFERENCES HISTORIAL(idHistorial), FOREIGn KEY (pkConfProg) REFERENCES CONFPROGRAMA(idConf));
As you can see, the way to add a patient here is tell the database the idPaciente explicitly.
So I used this code to insert a patient:
public long addPaciente(BDPaciente pac)
{
ContentValues cv = new ContentValues();
cv.put("idPaciente", 1);
cv.put("nombre", pac.getNombre());
cv.put("edad", 26);
try
{
db.insert("PACIENTE", null, cv);
return -1;
}
catch (SQLiteConstraintException e)
{
return -100;
}
}
As you can see, what I'm trying to do is insert a patient, and then, if it is inserted before, catch the Exception and throw it to my parent Window. The thing is that, the exception is thrown, but not catched. And the program says:
Error inserting nombre=blabla edad=25 idPaciente=1
android.database.SQLiteConstraintException: error code 19: constraint failed
I know that it's something about the duplication on the primary key, but I wanna do so!
Flo, thanky you for your answer, but yes, I created the table, but what I didn't post, is that I have a method for erasing all databases and then creating them again whenever I press a button like this:
db.execSQL(DROP_TABLE_HISTORIAL);
db.execSQL(DROP_TABLE_MEDICO);
db.execSQL(DROP_TABLE_CONF);
db.execSQL(DROP_TABLE_PACIENTE);
So yes, I'm sure. But what Sarmand answered works for me, so thank you for your help :-)
Sorry, but I can't vote... Don't have enough points >_<
If you want to duplicate primary key then dont declare it as primary key. Do it like this
CREATE TABLE IF NOT EXISTS PACIENTE(idPaciente INTEGER , ....);