I have these two tables in my android app: 'account' and 'person' .
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("create table account "
+ "(accountId integer primary key autoincrement,bank_name text,hesab_num text unique,cart_num text unique,cvv2 text,expire_date date , pId integer)");
db.execSQL("create table person (personId integer primary key autoincrement,name text)");
}
.
account:
ACCOUNT_COLUMN_BANK
ACCOUNT_COLUMN_HESAB
ACCOUNT_COLUMN_CART
ACCOUNT_COLUMN_CVV2
ACCOUNT_COLUMN_EXPIRE_DATE
ACCOUNT_COLUMN_P_ID // foreign key for person
person:
PERSON_COLUMN_NAME
and i have this method in android dbHelper class:
public boolean insertAccount(Person person, Bank bank) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues bankValues = new ContentValues();
ContentValues personValues = new ContentValues();
personValues.put(PERSON_COLUMN_NAME, person.getName());
long id = db.insert(PERSON_TABLE_NAME, null, personValues); // get id of person
bankValues.put(ACCOUNT_COLUMN_BANK, bank.getBankName());
bankValues.put(ACCOUNT_COLUMN_HESAB, bank.getAccountNumber());
bankValues.put(ACCOUNT_COLUMN_CART, bank.getCardNumber());
bankValues.put(ACCOUNT_COLUMN_CVV2, bank.getCvv2());
bankValues.put(ACCOUNT_COLUMN_EXPIRE_DATE, bank.getExpireDate()
.toString());
bankValues.put(ACCOUNT_COLUMN_P_ID, (int) id); // set id of person in account table
db.insert(ACCOUNT_TABLE_NAME, null, bankValues);
return true;
}
most of the times that i call this method , foreign key in account table is null. why? and what i must do ?
point: foreign key can be Repetitious , because a person can have many account.
Related
I am new in Android development.Please help me How can i store columns name in Sqlite database dynamically.
Create database below here:
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table contacts " +
"(id integer primary key, name text,phone text,email text, street text,place text)"
);
}
And insert query below here:
public boolean insertContact (String name, String phone, String email,String street,String place)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.insert("contacts", null, contentValues);
return true;
}
you can use ALTER TABLE function on your onUpgrade() method, like this :
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// If you need to add a column
if (newVersion > oldVersion) {
db.execSQL("ALTER TABLE foo ADD COLUMN new_column INTEGER DEFAULT 0");
}
}
Obviously, the SQLite will differ depending on the column definition
You do not need to provide a value for every column in your table to insert a new row. You can just change the code in your method to:
public long insertContact(ContentValues contentValues) {
return db.insert("contacts", null, contentValues);
}
Let the calling function decide which values it wants to insert, which can be all, some or none of the available columns. Any values not specified will be null in the table. For example if calling function does:
EditText name, email;
// ...
ContentValues values = new ContentValues();
values.put("name", name.getText().toString());
values.put("email", email.getText().toString());
insertContact(values);
will insert a new row in the database with "name" and "email" filled in and the rest of the columns null.
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 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 table with 2 columns, a numeric id and unique text. Created like this:
String CREATE_MY_TABLE = "CREATE TABLE " + TABLE_TEST + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_FOO + " TEXT UNIQUE"
+ ")";
db.execSQL(CREATE_MY_TABLE);
I want that when I insert KEY_FOO value and it's already in the db, nothing happens. But what I get is that the id is always incremented. No new row is inserted, that's good, but the id is autoincremented.
What I'm doing to insert is as follows:
db.insertWithOnConflict(TABLE_TEST , null, values, SQLiteDatabase.CONFLICT_NONE);
I tried CONFLICT_IGNORE, CONFLICT_ABORT, CONFLICT_ROLLBACK, all the same.
The reason I need this is because other table has a foreign key on this id, thus if the id is changed, the other table points nowhere.
How I just say to let the existing entry untouched?
Try this way. In your dbhelper class write the method like following to insert.
public int insertData(String desc) {
db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
try {
db.beginTransaction();
cv.put(KEY_FOO, desc);
db.insertOrThrow(TABLE_TEST, null, cv);
db.setTransactionSuccessful();
} catch (Exception ex) {
return 1;
} finally {
db.endTransaction();
db.close();
}
return 0;
}
Then from your actvity you call this method with the parameter value of KEY_FOO. This method will return 1 if the exception is occurs (If you try insert a unique value) and it will return 0 if the transaction is successfull.
I hope this way will help you. Let me know if any problem.
I inserted EditText value in database, Please help me how to get all the data in table and show it in a next Activity, please help me. I use the following code for inserting:
private static final String DATABASE_CREATE = "create table pill (id integer primary key autoincrement, "
+ "med VARCHAR, " + "dose1 VARCHAR,"+"dose2 VARCHAR,"+"dose3 VARCHAR);";
// ---insert data into the database---
public long insertData(String med, String dose1,String dose2,String dose3) {
ContentValues initialValues = new ContentValues();
initialValues.put(Med, med);
initialValues.put(Dose1, dose1);
initialValues.put(Dose2, dose2);
initialValues.put(Dose3, dose3);
return db.insert(DATABASE_TABLE, null, initialValues);
}
med, dose1, dose2, dose3 are the values from the EditText which is in another class.
You have to use:
db.query()
See that
Query only the first data from a table