I have a problem with SQLite in android , I tried a simple insert in a table but I have an exception and in the exception I read this :
INSERT INTO Biblio(Auteur,Image,Livre) VALUES (?,?,?)
this is my method :
public void AddBook(Bibliothèque bibliothèque)
{
SQLiteDatabase db=this.getWritableDatabase();
//this.open();
ContentValues values=new ContentValues();
values.put(KEY_Auteur,bibliothèque.getNomAuteur());
values.put(KEY_Livre,bibliothèque.getNomLivre());
values.put(Key_photo,bibliothèque.geturiimage().toString());
db.insert("Biblio",null,values);
db.close();
}
and this is my variables:
private static final String TABLE_Nom = "Biblio";
private static final String KEY_ID = "id";
private static final String KEY_Auteur = "Auteur";
private static final String KEY_Livre = "Livre";
private static final String Key_photo="Image";
the problem I don't know why but db.insert invert beetween Image and Livre and because of that I have an exception and I don't know why the value that I insert are ? ? ? in debug I can see that the value are correct ! . normaly the true expression must be :
INSERT INTO Biblio(Auteur,Livre,Image) VALUES (cc,test,(uri of picture))
this is the entire exception :
2927-2927/com.example.myapplication4.app E/SQLiteLog﹕ (1) table Biblio has no column named Livre
05-15 02:53:54.436 2927-2927/com.example.myapplication4.app E/SQLiteDatabase﹕ Error inserting Auteur=gsopfkgop Image=content://media/external/images/media/10 Livre=fhoksgkp
android.database.sqlite.SQLiteException: table Biblio has no column named Livre (code 1): , while compiling: INSERT INTO Biblio(Auteur,Image,Livre) VALUES (?,?,?)
USE This Query to Create Table.
db.execSQL
("CREATE TABLE Biblio (id INTEGER PRIMARY KEY AUTOINCREMENT ,Auteur TEXT,Livre TEXT,Image TEXT)");
then You have to insert record using Below code:
public void AddBook(Bibliothèque bibliothèque)
{
SQLiteDatabase db=this.getWritableDatabase();
//this.open();
ContentValues values=new ContentValues();
values.put(Auteur,bibliothèque.getNomAuteur());
values.put(Livre,bibliothèque.getNomLivre());
values.put(Image,bibliothèque.geturiimage().toString());
db.insert("Biblio",null,values);
db.close();
}
I hope its useful to you..
2927-2927/com.example.myapplication4.app E/SQLiteLog﹕ (1) table Biblio has no column named Livre
Your table doesn't have a column named Livre, either you have a spelling mistake here, in your table creation code, or you haven't defined a column named Livre.
You should try to reinstall your app?
Also, if your db schema has been changed after your app installed in your test device, you have to increase db version parameter to invoke onUpdate() method or reinstall your app to invoke onCreate().
Related
I'm trying to insert rows in my Student Table which contains two rows : ID and Name
Here is the addHandler function which is implemented in MyDBHandler class :
public void addHandler(Student student) {
ContentValues values = new ContentValues();
values.put(COLUMN_ID, student.getID());
values.put(COLUMN_NAME, student.getStudentName());
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_NAME, null, values);
db.close();
}
The onCreate method is :-
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + COLUMN_ID + " INTEGER PRIMARY KEY ," + COLUMN_NAME + " TEXT )";
db.execSQL(CREATE_TABLE);
}
The attributes of MyDBHandler class which extends SQLiteOpenHelper :
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "studentDB.db";
public static final String TABLE_NAME = "Student";
public static final String COLUMN_ID = "StudentID";
public static final String COLUMN_NAME = "StudentName";
I have a ADD Button in my activity_main.xml file and here is the code behind :
public void add(View view){
MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1);
int id = Integer.parseInt(studentIdText.getText().toString());
String name = studentNameText.getText().toString();
Student student = new Student(id, name);
dbHandler.addHandler(student);
studentIdText.setText("");
studentNameText.setText("");
}
The app is running perfectly but when i want to insert a row in the table , i get the following errors in Run Tab :
E/SQLiteLog: (1) table Student has no column named StudentID
E/SQLiteDatabase: Error inserting StudentName=yassine StudentID=10
android.database.sqlite.SQLiteException: table Student has no column named StudentID (code 1): , while compiling: INSERT INTO Student(StudentName,StudentID) VALUES (?,?)
#################################################################
Error Code : 1 (SQLITE_ERROR)
Caused By : SQL(query) error or missing database.
(table Student has no column named StudentID (code 1): , while compiling: INSERT INTO Student(StudentName,StudentID) VALUES (?,?))
#################################################################
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1093)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:670)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1607)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1479)
at com.example.test.MyDBHandler.addHandler(MyDBHandler.java:48)
at com.example.test.MainActivity.add(MainActivity.java:40)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:5246)
at android.widget.TextView.performClick(TextView.java:10566)
at android.view.View$PerformClick.run(View.java:21256)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6917)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Any recommendations ?
Your issue is very likely a mis-conception in regard to the onCreate method. That is it onCreate doesn't run every time the App is run. onCreate will only run if the database doesn't actually exist. If the database has already been created by another previous run of the App then the onCreate method is not run.
As such any changes made to the structure of the database, as typically applied in the onCreate method will not be applied.
It would appear that you have added the defnition for the StudentId column, to the code in the onCreate method, after the App has been run.
As long as you have no data that needs to be preserved (which is very likely) then the simplest solution is to do 1 of the following :-
delete or clear the App's data (via settings/Apps)
uninstall the App
and then rerun the App, the database will then be created using the code as per the modified onCreate code.
I have one column in SQLite database.It stores Text value.When new value is inserted I need to delete the previous value and add new value in Database. This is method in Class which extends SQLiteOpenHelper to update the column.
public void updateOffline(String data){
SQLiteDatabase db=this.getWritableDatabase();
String updateQuery="UPDATE "+OFFLINE_MODE +" SET "+OFFLINE_DATA+" = "+ data;
db.execSQL(readQuery);
}
where data is the String I need to UPDATE
I am calling this method in one of Fragment as
db.updateOffline(tempArray.toString());
I am getting error as
android.database.sqlite.SQLiteException: no such column: {"name":"jjajaja","phone":"4545454545","no_people":"2","booktime":"12:46 pm"} (code 1): , while compiling: UPDATE offlinedata SET offlinequeue =[{"name":"jjajaja","phone":"4545454545","no_people":"2","booktime":"12:46 pm"}]
How to resolve this ?
You cannot just dump a JSON string inside SQL and expect it to be syntactically valid.
String literals in SQL go in 'single quotes' but then just dumping data in SQL i quotes exposes you to SQL injection. Use variables instead.
If you use SQLiteDatabse update() method with ContentValues, it uses variables automatically for you.
If you want to keep on working in raw SQL, change
String updateQuery="UPDATE "+OFFLINE_MODE +" SET "+OFFLINE_DATA+" = "+ data;
db.execSQL(updateQuery);
to something like
String updateQuery="UPDATE "+OFFLINE_MODE +" SET "+OFFLINE_DATA+" = ?";
db.execSQL(updateQuery, new Object[] { data });
I'm working on a android program with SQLite. I'm trying to create a datebase with two tables related by a foreign key, and I want to automaticaly populate one entry of the mother table using the insert funcion. But this generate an SQLite error.
Here is the funcion to insert an entry into the mother class
private long new_event(SQLiteDatabase db)
{
ContentValues values = new ContentValues();
long id = db.insert("EVENT",null,values);
return id;
}
Here is the function to insert an entry into the child class
public long new_specific_event(SQLiteDatabase db)
{
long id_event = new_event(db);
ContentValues values = new ContentValues();
values.put("id_event", id_event);
values.put("whatsoever", "whatsoever");
long id = db.insert("SPECIFIC_EVENT",null,values);
return id;
}
Here is the mother table
CREATE TABLE EVENT (id INTEGER PRIMARY KEY AUTOINCREMENT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
and here is the child table
CREATE TABLE SPECIFIC_EVENT (id INTEGER PRIMARY KEY AUTOINCREMENT, id_event NUMBER,whatsoever TEXT,FOREIGN KEY(id_event) REFERENCES EVENT(id));
This result into the following error
android.database.sqlite.SQLiteException: near "null": syntax error (code 1): , while compiling: INSERT INTO EVENT(null) VALUES (NULL)
I could do it using this and the db.execSQL() funcion, but then I have no access to the id of the entry I just create.
So, how can I use the insert funcion to insert an entry with just default value?
With ContentValues you need to put at least one value. To get a default value, put a null for a value for a column:
ContentValues values = new ContentValues();
values.putNull("_id");
long id = db.insert("EVENT",null,values);
Inserting a completely empty row is not possible, so the insert() method has the parameter nullColumnHack to allow you to specify a column that gets a NULL value in this case:
ContentValues values = new ContentValues();
long id = db.insert("EVENT", "_id", values);
i'm trying to insert some data into a SQLite3 Database on an Android system.
This method should takes three strings and insert them into a database:
public void createEntry(String description, String reps, String weight)
{
ContentValues cv = new ContentValues();
cv.put(KEY_DESCRIPTION, description);
cv.put(KEY_REPS, reps);
cv.put(KEY_WEIGHT, weight);
sqlDB.insert(DATABASE_TABLE, null, cv);
}
The columns(KEY_DESCRIPTION,..) are all defined as TEXT NOT NULL and I also added an auto incrementing column.
In my main activity I'm using this code to get input from EditText Widgets
String description = sqlDescription.getText().toString();
then I'm creating an instance of my DB class:
DB entry = new DB(MainActivity.this);
entry.open();
entry.createEntry(description, reps, weight);
entry.close();
open() uses the SQLiteOpenHelper and sets up database:
public DB open()
{
sqlHelper = new dbHelper(sqlContext);
sqlDB = sqlHelper.getWritableDatabase();
return this;
}
But when I call this method:
entry.createEntry(description, reps, weight);
I get following error:
(1) near "Table": syntax error
E/SQLiteDatabase(19344): Error inserting Description=test Weight=tesz Reps=test
E/SQLiteDatabase(19344): android.database.sqlite.SQLiteException: near "Table": syntax error
(code 1): , while compiling: INSERT INTO Table(Description,Weight,Reps) VALUES (?,?,?)
TABLE is a reserved word in SQL; you should not use it as the name of the table.
Try changing it to:
private static final String DATABASE_TABLE = "myTable";
I created a sql lite database with the following columns:
static final String dbName="demoDB";
static final String tableName="Employees";
static final String colID="EmployeeID";
then
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE "+tableName+" ("+colID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
colName+" TEXT, "+colAge+" Integer);");
}
I want to select all the records in the database like this and display them in a gridview:
SQLiteDatabase db=this.getWritableDatabase();
Cursor cur= db.rawQuery("Select "+colName+", "+colAge+" from "+tableName, new String [] {});
String [] from=new String []{DatabaseHelper.colName,DatabaseHelper.colAge};
int [] to=new int [] {R.id.colName,R.id.colAge};
SimpleCursorAdapter sca=new SimpleCursorAdapter(this,R.layout.gridrow,c,from,to);
GridView grid=(GridView)findViewById(R.id.grid);
grid.setAdapter(sca);
but i receive the following exception:
java.lang.IllegalArgumentException: column '_id' does not exist.
the db table does not have a column with name '_id'
so what is wrong with this code
Thanks
a workaround to this problem is to use select statment like this
select EmpId as _id
cause the adapter requires a column with the name _id as you said
thanks
When using an adapter, your Table must always have the Primary Key Column named as "_id"
Just change
static final String colID="EmployeeID";
to
static final String colID="_id";
Cheers!
CursorAdapters require an INTEGER PRIMARY KEY column named _id (available from BaseColumns).
Try this way
SELECT _ID as _ID,_ID as _id , cont_type ,.... FROM DATABASE_TABLE ;
When _ID only ,Message is column '_id' does not exist.
When _id only ,Message is column '_ID' does not exist.
I tried _id (lower case) instead of _ID (Uppercase) solves the problem. Make sure to recreate the DB once again with _id (lowercase)
Thank you very much
If you loading your database from assets: After you have changde your id to _id in the database base table, and your loading it from assets folder that you uninstall the app first, otherwise you will be using your old database.