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);
Related
I am trying to insert data in an SQLite database from different places in different columns at a time. When I view the database, each insert takes one row. My databases lookes like this:
How do I achieve this? Any suggestions?
In order to insert a new row within your database, you need to add the following code into the Java class that manages your SQLite database:
public long insertRow(String name, String email)
{
ContentValues contentValues = new ContentValues();
contentValues.put(rowName, name);
contentValues.put(rowEmail, email);
return database.insert(databaseTable, null, contentValues);
}
The variable database refers to the database you attempting to insert the row. The variable databaseTable refers to the table you want to insert the row into. If you are attempting to update an existing column, you need to add the following code into the Java class that manages your database:
public boolean updateRow(long id, String name, String email)
{
ContentValues contentValues = new ContentValues();
contentValues.put(rowName, name);
contentValues.put(rowEmail, email);
return database.update(databaseTable, contentValues, rowId + “=” + id, null) > 0;
}
In order to call this function, you need to pass the id of the row and the desired values to pass in order to update them.
I'm working on a project and don't understand this part of this code that I found online. (I have also looked at other examples and they do the exact same thing but I don't quite understand why)
When they are inserting something into the table, they have no value for the primary key. Could someone explain to me why that is the case?
Here is 2 examples of code that I found that do what I have stated above.
Thanks.
// As you can see a contact has 3 attributes.
int _id;
String _name;
String _phone_number;
// Where they create a table. As you can see the primary key is ID
#Override
public void onCreate(SQLiteDatabase db)
{
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Adding new contact
// This is what I don't understand. Why don't they get an ID for the contact.
// They only have values for the name and phone number when they insert it into the table.
public void addContact(Contact contact)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone Number
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
Here's another example but this is using a book.
A book has 3 attributes, an id (the primary key), an author and the book name. And once again, they don't get the value for the primary key.
public void addBook(Book book)
{
Log.d("addBook", book.toString());
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put(KEY_TITLE, book.getTitle()); // get title
values.put(KEY_AUTHOR, book.getAuthor()); // get author
// 3. insert
db.insert(TABLE_BOOKS, // table
null, //nullColumnHack
values); // key/value -> keys = column names/ values = column values
// 4. close
db.close();
}
because primary key is Autoincrement as it is an alias for ROWID.
from the documentation:
In SQLite, table rows normally have a 64-bit signed integer ROWID
which is unique among all rows in the same table. (WITHOUT ROWID
tables are the exception.)
You can access the ROWID of an SQLite table using one the special
column names ROWID, ROWID, or OID. Except if you declare an ordinary
table column to use one of those special names, then the use of that
name will refer to the declared column not to the internal ROWID.
If a table contains a column of type INTEGER PRIMARY KEY, then that
column becomes an alias for the ROWID. You can then access the ROWID
using any of four different names, the original three names described
above or the name given to the INTEGER PRIMARY KEY column. All these
names are aliases for one another and work equally well in any
context.
When a new row is inserted into an SQLite table, the ROWID can either
be specified as part of the INSERT statement or it can be assigned
automatically by the database engine. To specify a ROWID manually,
just include it in the list of values to be inserted. For example:
so in the examples you have given id is being assigned by database engine. for most of the use cases this is good enough.
You can create the table like
static final String DATABASE_CREATE = "create table "+TABLE_NAME+"( ID integer primary key autoincrement,user_name text,user_phone text,user_email text); ";
Then it will increment automatically
See this link http://www.freakyjolly.com/android-sqlite-integration/
http://www.freakyjolly.com/android-sqlite-how-to-insert-rows-in-database/
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().
I am using an auto_increment primary key for the 'user' table. My question is, can I use that same User ID (Primary Key), as the primary key for the 'user log' table? Are there any major reasons why I shouldn't do this?
My idea on implementation:
To do this I would have the user create an entry (name,email pass, etc), once that's complete the 'User Log' is created by taking the key from the 'user' table and passing that into the 'user log' entry creation method as a foreign key? Or would it still be called the primary key at this point?
A simple code example would be great. Here is what I have:
// Create the table
public void onCreate(SQLiteDatabase db) {
// SQL statement to create book table
String CREATE_USER_TABLE = "CREATE TABLE userLog ( " +
"userID INTEGER PRIMARY KEY, " +
"date TEXT )";
// create directory table
db.execSQL(CREATE_USERLOG_TABLE);
}
//Add entry to the table using value from user
public void addEntry(UserLogEntry entry, UserEntry userEntry){
Log.d("addEntry", entry.toString());
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put(KEY_USERID, userEntry.getUserID());
values.put(KEY_DATE, entry.getDate());
// 3. insert
db.insert(TABLE_USERLOG, // table
null, //nullColumnHack
values); // key/value -> keys = column names/ values = column values
// 4. close
db.close();
}
So that won't work thanks to CL for pointing that out. I'll need to have a unique key and add the userid's as a new column. I'll just pull the userid from the users table when creating the userslog and that should solve that issue.
I have a little Problem with an insert-Statement in my Android-App.
Here is the code:
public void addNote(Note noteItem, int modulNummer){
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NOTE, noteItem.getNote());
cv.put(COLUMN_NOTEBESCHREIBUNG, noteItem.getBeschreibung());
cv.put(COLUMN_MODULID_FK, modulNummer);
db.insert(NOTETABLE, null, cv);
}
Now my problem. The first column in my table is an auto increment pk. And so i want to skip the first column and i want to begin the insert in the second column. How can i skip this first column?
Update
I've already deleted the .put for the first column. "COLUMN_NOTE" is my second column.
My table-structure looks like this:
id INTEGER AUTO INCREMENT
note double
beschreibung TEXT
modul_id INTEGER
UPDATE 2
I don't know why, but now it works. Thx for your help guys.
If you have a table like the following one:
private final String TAB_GROUP_ADD = "CREATE TABLE groups (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, description TEXT NOT NULL);";
And you use the following insert command:
ContentValues values = new ContentValues();
values.put(K_TITLE, title);
values.put(K_DESCRIPTION, description);
db.insert(TAB_GROUP, null, values);
Everything should go fine. The primary key field "id" will no be filled in by Java and the SQLite Database will do it for you.