Multiple tables in sqflite - dart

im very new to flutter, and i just want to setup a SQLite database with multiple tables.
my research below.
thanks in advance.
How to create multiple tables in a database in sqflite?
await db.execute('''
create table $reminderTable (
$columnReminderId integer primary key autoincrement,
$columnReminderCarId integer not null,
$columnReminderName text not null,
$columnReminderNotifyMileage integer not null,
$columnReminderEndMileage integer not null
)''');
await db.execute('''
create table $carTable (
$columnCarId integer primary key autoincrement,
$columnCarTitle text not null
)''');
Unknown error calling sqlite3_step (10: disk I/O error) rs

You can just combine multiple db.execute calls for example
void _createDb(Database db, int newVersion) async {
await db.execute(
'CREATE TABLE $noteTable($colId INTEGER PRIMARY KEY AUTOINCREMENT, $colTitle TEXT, '
'$colDescription TEXT, $colPriority INTEGER, $colDate TEXT)');
await db.execute(
'CREATE TABLE $noteTable($colId INTEGER PRIMARY KEY AUTOINCREMENT, $colTitle TEXT, '
'$colDescription TEXT, $colPriority INTEGER, $colDate TEXT)');
}

Related

Why doesn't init script create every table in the script?

I am trying to make an init script for MariaDB, using docker-compose.
Only the 3 first tables are created, so player_team_relation and player table are not created.
create table if not exists user
(
user_id varchar(255) primary key,
username varchar(30) not null,
password_hash varchar(255) not null
);
create table if not exists history
(
history_id bigint auto_increment primary key,
user_id varchar(255) not null,
game_date timestamp not null,
constraint user_history_constraint foreign key (user_id) references user (user_id)
);
create table if not exists team
(
team_id bigint auto_increment primary key,
history_id bigint not null,
player_name varchar(30) not null,
score bigint not null,
hasWon bool not null,
constraint history_team_constraint foreign key (history_id) references history (history_id)
);
create table if not exists player_team_relation
(
player_id bigint not null primary key,
team_id bigint not null primary key,
constraint player_ptr_constraint foreign key (player_id) references player (player_id),
constraint team_ptr_constraint foreign key (team_id) references team (team_id)
);
create table if not exists player
(
player_id bigint auto_increment primary key,
user_id varchar(255) not null,
player_name varchar(30) not null,
wins int not null,
losses int not null,
score bigint not null,
constraint user_player_constraint foreign key (user_id) references user (user_id)
);
I have tried creating the database many times by deleting the volume and creating a new container.
Another example why error checking is always recommended:
The statement
create table if not exists player_team_relation
(
player_id bigint not null primary key,
team_id bigint not null primary key,
...
will fail, since it's not possible to define multiple primary keys per table. For more information on primary keys please check the documentation.
About your column definitions: Are you sure you want to use BIGINT (signed integer) instead of BIGINT UNSIGNED for auto_increment? Do you really need BIGINT? The maximum value of INTEGER UNSIGNED is 4294967295 - more than half of the world's population.

Flutter DatabaseException(UNIQUE constraint failed)

I`m trying to insert some data into sqflite table but there is an error while executing insert query
await db.execute(
'CREATE TABLE $catrgoryTable($category_id INTEGER PRIMARY KEY UNIQUE , $colDeviceTypeId INTEGER, '
'$room_id INTEGER)');
print('category created!');
and here is the Error
SqfliteDatabaseException (DatabaseException(UNIQUE constraint failed: category_Table.category_id (code 1555)) sql 'INSERT INTO category_Table (category_id, device_type_id, room_id) VALUES (?, ?, ?)' args [1, 1, 1]})
Thanks for any help:)
The table category_Table has a unique constraint field on it, the error shows that you tried to enter a value for category_id that it already exists, which violates primary key's uniqueness constraint for this field. Only one row can exist with a given ID value. So If you're trying to insert a row, be sure that your category_id have a unique value, or if you don't care about generating ids by yourself, you can add AUTOINCREMENT setting to your category_id column definition. This way it will be filled automatically and each row will have its own unique value.
static Future<void> insert(String table, Map<String, dynamic> data) async {
final db = await DBHelper.database();
db.insert(table, data, conflictAlgorithm: sql.ConflictAlgorithm.replace);
}
here is my code is thought if I use conflict algorithm replace it would replace that unique value ?
In the insert function of database. Add
conflictAlgorithm: ConflictAlgorithm.replace.
it worked for me

Creating a 'join' table - sqlite3

I think I'm pretty close on this one, but can't get it to click.
I've got two simple tables set up.
Table A:
CREATE TABLE customer(
id INTEGER PRIMARY KEY,
first_name TEXT,
last_name TEXT,
email TEXT UNIQUE NOT NULL,
password TEXT NOT NULL,
create_time TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
I've got two rows of data populating correctly in Table A.
Table B:
CREATE TABLE address(
...> id INTEGER PRIMARY KEY,
...> street_address_1 TEXT NOT NULL,
...> street_address_2 TEXT,
...> street_address_3 TEXT,
...> city TEXT NOT NULL,
...> state TEXT NOT NULL,
...> zip TEXT NOT NULL);
And I've successfully imported a CSV file into that table.
I'm trying to create a 3rd table that joins Table A to Table B with the use of Foreign Keys.
I can create the table with the code below, but when I try to select the table, I'm getting a blank, which means I'm obviously doing something wrong. I'm expecting to see data where the two tables overlap on mutual Id numbers, i.e. where the ID from customer = Id from address I'd like to see the data from both tables for those rows appear in Table C.
Table C (the join table):
CREATE TABLE customer_address(
id INTEGER PRIMARY KEY,
customer_id INTEGER,
address_id INTEGER,
first_name TEXT NOT NULL,
last_name TEXT NOT NULL,
email TEXT NOT NULL,
password TEXT NOT NULL,
street_address_1 TEXT NOT NULL,
street_address_2 TEXT,
street_address_3 TEXT,
city TEXT NOT NULL,
state TEXT NOT NULL,
zip TEXT NOT NULL,
FOREIGN KEY (customer_id) REFERENCES customer(id),
FOREIGN KEY (address_id) REFERENCES address(id)
);
Thanks!
I imported the data to the address table using this:
sqlite> .mode csv
sqlite> .import address.csv address
I manually typed in data to the first table using this:
insert into customer(first_name, last_name, email, password)
values('Ad','Mac','a.Mac#gmail.com','Mab'),('Brian','Obrien','bob#example.com','123456');
Don't duplicate the data in your join table (often called a bridge table). This should do for Table C:
CREATE TABLE customer_address(
id INTEGER PRIMARY KEY,
customer_id INTEGER,
address_id INTEGER,
FOREIGN KEY (customer_id) REFERENCES customer(id),
FOREIGN KEY (address_id) REFERENCES address(id));
Duplicating columns is bad practice because it 1)defeats the purpose of using a relational model; 2)can lead to conflicting records if information is updated or deleted in one table, but not another.
Furthermore, you shouldn't have street_address_1, street_address_2, street_address_3 all in the same table. That's a violation of First Normal Form. Think of it this way, can a person have more than three addresses? Can they have two addresses in different cities? Do all three of those addresses have the same zip?

how to fetch records from two tables using foreign key

create table studentsDetail (
student_id integer primary key,
rollno text,
name text,
stream text,
school text
);
create table studentsInfo (
studentinfo_id integer primary key,
stdetail_info_id integer,
fathername text,
mothername text,
age text,
address text,
FOREIGN KEY(stdetail_info_id) REFERENCES studentsDetail(student_id)
);
I want to fetch record from both table using foreign key. How can I do it easily?
Something like this:
SELECT
studentsDetail.name, studentsDetail.school,
studentsInfo.age, studentsInfo.address
FROM
studentsDetail INNER JOIN studentsInfo
ON studentsDetail.student_id = studentsInfo.stdetail_info_id

sqlite insert with primary key

I use sqlite(3.7.4) in iphone.
I create a table like:
create table A (UserName varchar (50) primary key, Num integer);
Then I insert the record below twice:
('abc',1);
Normally there should be only one record in DB.
However I found in the DB
(abc,1);
( ,1);
I'm confused that as UserName is primary key and why there are two records!
I don't know what's the problem.
Can anyone help me?
thank you.
Why you want use username as primary key. Primary key should unique identify record. What is why when you inserted twice in second time you have primary key constraint violation
create table A (UserName varchar (50) primary key, Num integer, unique (UserName));

Resources