how to use join in sqlite flutter - flutter

i'm a beginner in flutter app development, currently i'm making a quiz maker app for a college project , so i have created a quiz table which contains the quiz related information such as the id and the title , and then i created the question table which contains the questions , the answer choices , the id , and finally the quiz id as a foreign key , could anyone please tell me how can make insert the questions inside that specific quiz . here's a glimpse of my database (qcm is the quiz)
`
class DB_helper {
DB_helper._();
static final DB_helper instance = DB_helper._();
static late Database _database;
Future<Database> get database async {
if (_database != null) return _database;
_database = await initDB();
return _database;
}
initDB() async {
WidgetsFlutterBinding.ensureInitialized();
return await openDatabase(
join(await getDatabasesPath(), 'qcm.db'),
onCreate: (db, version) async {
await db.execute(
"CREATE TABLE prof(nom TEXT,email TEXT,description TEXT)"
);
await db.execute(
"CREATE TABLE question(question_id TEXT PRIMARY KEY,question TEXT,quiz_id TEXT,FOREIGN KEY(quiz_id)REFERENCES quiz(quiz_id))");
await db.execute(
"CREATE TABLE qcm(qcm_id TEXT PRIMARY KEY,titre TEXT,)"
);
await db.execute(
"CREATE TABLE choix(choix_id TEXT PRIMARY KEY,choix TEXT,valeur INTEGER,question_id TEXT,FOREIGN KEY(question_id)REFERENCES question(question_id))"
);
},
version: 1,
);
}
void insertprofil(Prof prof) async {
final Database db = await database;
await db.insert(
'prof',
prof.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
void insertquestion(Question question) async {
final Database db = await database;
await db.insert(
'question',
question.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
void insertqcm(Qcm qcm) async {
final Database db = await database;
await db.insert(
'qcm',
qcm.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}`

Related

Error: The method 'execute' isn't defined for the class 'Type'

The method 'execute' isn't defined for the type 'Type'
How can I solve the error I get above?
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
class LiteDb {
static Database? _db;
Future<Database?> get getInstance async {
if (_db == null) {
_db = await instance();
return _db;
else {
return _db;
}
}
Future<void> addSalaryColumn() async {
final db = await Database;
await db.execute(
"ALTER TABLE PERSON ADD COLUMN salary INTEGER DEFAULT 0"
);
}
instance() async {
Get a location using getDatabasesPath
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'lite_sql.db');
open the database
Database database = await openDatabase(path, version: 2,
onCreate: (Database db, int version) async {
When creating the db, create the table
await db.execute(
CREATE TABLE PERSON (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER);
CREATE TABLE ACCOUNT (id INTEGER PRIMARY KEY AUTOINCREMENT, PERSON_ID INTEGER NOT NULL, ACCOUNT INTEGER NOT NULL, VALUE REAL);
''');
print('Text Database has been created');
},
onUpgrade: (Database db, int oldVersion, int newVersion) async {
if (newVersion >= 2) {
await db.execute('''
ALTER TABLE PERSON ADD COLUMN salary REAL NULL
''');
}
}
);
print(' Database connected');
return database;
}
inquiry(String sqlTxt) async {
Database? db = await getInstance;
Get the records
List<Map> list = await db!.rawQuery(sqlTxt);
return list;
}
insert(String sqlTxt) async {
Database? db = await getInstance;
Insert some record
int count = await db!.rawInsert(sqlTxt);
return count;
}
update(String sqlTxt) async {
Database? db = await getInstance;
Update some record
int count = await db!.rawUpdate(sqlTxt);
return count;
}
delete(String sqlTxt) async {
Database? db = await getInstance;
Delete some record
int count = await db!.rawDelete(sqlTxt);
return count;
}
}

Share data while the Internet is available using flutter

I have a query I would like to store some data in the cache in the event that the phone is not connected to the Internet and when I connect to the Internet, it is sent to the server. I would like to know the best scenario for this case...
And thank u.
You can try saving the data to the server and on failure you can write it in cache. Like
var response = await http.post(Uri.parse("api url here"),
body: json.encode(body),
);
if(response.statusCode != 200)
{
//save data in local like for example
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString("apiBody", json.encode(body);
}
If you need to store or receive a large amount of data, consider to store this datas in a localdatabase like sqflite: https://pub.dev/packages/sqflite
base on SQLLite, you can store and manipulate data with SQL queries.
Here is an example DB helper call that manipulate customer datas:
class DBProvider {
DBProvider._();
static final DBProvider db = DBProvider._();
late Database _database;
Future<Database> get database async {
_database = await initDB();
return _database;
}
initDB() async {
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(
documentsDirectory.path,
"andidoor.db",
);
return await openDatabase(
path,
version: 2,
onOpen: (db) {},
onCreate: createDatabase,
onUpgrade: upgradeDatabase,
);
}
upgradeDatabase(Database db, int oldVersion, int newVersion) async {
print('Upgrade Database ...');
}
createDatabase(Database db, int version) async {
print('Create Database ...');
await db.execute("CREATE TABLE customers ("
"id INTEGER PRIMARY KEY,"
"user_id INTEGER,"
"company TEXT,"
"address_1 TEXT,"
"address_2 TEXT,"
"address_3 TEXT,"
"zipcode TEXT,"
"city TEXT,"
"country TEXT,"
"email TEXT,"
"phone TEXT,"
"status INTEGER,"
"synced TEXT"
")");
/**
* Customers helper functions
*/
Future<List<dynamic>> getCustomers() async {
Database db = await database;
return await db.rawQuery('SELECT * FROM customers ');
}
Future<void> populateCustomers(List<dynamic> customers) async {
final completer = Completer();
await deleteAllcustomers();
for (var i = 0; i < customers.length; i++) {
await addCustomer(Customer.fromMap(customers[i]), true);
}
completer.complete();
return completer.future;
}
Future<dynamic> deleteAllcustomers() async {
Database db = await database;
return await db.rawQuery('DELETE FROM customers');
}
Future<dynamic> deleteCustomer(String customerID) async {
final db = await database;
return db.delete(
"customers",
where: "id = ? ",
whereArgs: [customerID],
);
}
}
And in other dart file just use like this:
final db = DBProvider.db;
List<dynamic> allDatas = [];
allDatas = await db.getCustomers();

How to make sqflite database faster?

I am trying to developing an app. In this app I need a local database. I choose sqflite database but it is very slow. It is taking so much time to fetch and insert data. It is my database helper class. As you can see in code that I have lot of rows. I am new at asking question if you need more information you can comment.
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart' as sqf;
class DataBaseHelper {
static Future<sqf.Database> database() async {
final dbPath = sqf.getDatabasesPath();
return sqf.openDatabase(
join(await dbPath, 'habits_record.db'),
onCreate: (db, version) async {
await db.transaction((txn) async {
var batch = txn.batch();
await txn.execute(
'''CREATE TABLE habitTable(id INTEGER PRIMARY KEY, title TEXT, reason TEXT,plan TEXT, iconData TEXT,hour INTEGER, minute INTEGER, notificationText TEXT, notificationId INTEGER,alarmHour INTEGER, alarmMinute INTEGER)''',
);
await txn.execute(
'''CREATE TABLE event(id TEXT PRIMARY KEY, dateTime TEXT, habitId INTEGER)''',
);
await txn.execute(
'''CREATE TABLE note(id TEXT PRIMARY KEY, dateTime TEXT, habitId INTEGER, Note TEXT)''',
);
await batch.commit();
});
},
version: 1,
);
}
static Future<void> insertNote(Map<String, Object> data) async {
final db = await DataBaseHelper.database();
db.insert('note', data, conflictAlgorithm: sqf.ConflictAlgorithm.replace);
}
static Future<void> deleteNote(String id) async {
final db = await DataBaseHelper.database();
await db.delete(
'note',
where: 'id = ?',
whereArgs: [id],
);
}
static Future<List<Map<String, dynamic>>> fetchAndSetNotes() async {
final db = await DataBaseHelper.database();
return await db.query('note');
}
static Future<void> updateNote(Map<String, Object> newNote) async {
final db = await DataBaseHelper.database();
final batch = db.batch();
batch.update(
'note', newNote, where: 'id = ?',
whereArgs: [newNote['id']],
);
batch.commit(continueOnError: true);
}
static Future<void> insertEvent(Map<String, Object> data) async {
final db = await database();
await db.insert('event', data,
conflictAlgorithm: sqf.ConflictAlgorithm.replace);
}
static Future<void> deleteEvent(String id) async {
final db = await DataBaseHelper.database();
await db.delete(
'event',
where: 'id = ?',
whereArgs: [id],
);
}
static Future<List<Map<String, dynamic>>> fethEvent() async {
final db = await DataBaseHelper.database();
return await db.query('event');
}
static Future<void> insertHabit(Map<String, Object> data) async {
final db = await database();
await db.insert('habitTable', data,
conflictAlgorithm: sqf.ConflictAlgorithm.replace);
}
static Future<List<Map<String, dynamic>>> habits() async {
final db = await DataBaseHelper.database();
return await db.query('habitTable');
}
static Future<void> deleteHabit(int id) async {
final db = await DataBaseHelper.database();
await db.delete(
'habitTable',
where: 'id = ?',
whereArgs: [id],
);
}
static Future<void> updateHabit(Map<String, Object> oneHabit) async {
final db = await DataBaseHelper.database();
await db.update(
'habitTable',
oneHabit,
where: 'id = ?',
whereArgs: [oneHabit['id']],
);
}
}
Here is the ObjectBox vs Hive vs
Sqflite performance benchmarks.
You can decide which one you want to go with.
In CRUD operations, you can see that sqflite is very slow when comparing with others.
If sqflite has not the speed you want , you can use hive or objectbox.

I got issue when i wanna create db to sqflite, DatabaseException(Error Domain=FMDatabase Code=1 "no such table)

I wanna create db with sqflite but this no create and show something issue, Unhandled Exception: DatabaseException(Error Domain=FMDatabase Code=1 "no such table: todo" UserInfo={NSLocalizedDescription=no such table: todo}) sql 'SELECT * FROM todo WHERE id = ?' args [11], oke let's check it my db helper :
db helper
import 'package:sqflite/sqflite.dart';
import 'model.dart';
class DatabaseHelper {
//singleton base
static DatabaseHelper? _instance;
DatabaseHelper._internal() {
_instance = this;
}
factory DatabaseHelper() => _instance ??= DatabaseHelper._internal();
//TODO: add database name
static late Database _database;
//TODO: add get database
Future<Database> get databse async {
_database = await _initializeDatabase();
return _database;
}
//TODO: add db name
static String _tableName = 'todo';
//TODO: initialize db
Future<Database> _initializeDatabase() async {
final path = await getDatabasesPath();
final db = openDatabase('notes.db', version: 1, onCreate: (db, version) {
version:
1;
db.execute('''CREATE TABLE $_tableName(
id INTEGER PRIMARY KEY,
title TEXT,
description TEXT,
)''');
});
return db;
}
Future<void> insertData(Note note) async {
final Database db = await databse;
List<Map<String, dynamic>> result = await db.query(
_tableName,
where: 'id = ?',
whereArgs: [note.id],
);
await db.insert(_tableName, note.toJson());
}
//get
Future<List<Note>> getAllNotes() async {
final Database db = await databse;
List<Map<String, dynamic>> result = await db.query(_tableName);
return result.map((e) => Note.fromJson(e)).toList();
}
}

flutter sqflite clears table after hot restart

On creating my sqflite database,i create my table activity_table using the 'onCreate' parameter.
it starts with 0 records.
i can insert ,edit and delete records in it.
i can query and check the count of records. everything is working fine.
problem:
But after hot restart,the table is getting empty.
class ActivityDB {
static final ActivityDB instance = ActivityDB._internal();
ActivityDB._internal();
static Database? _database;
Future<Database> get database async {
if (_database != null) {
return _database!;
}
_database = await _init();
return _database!;
}
Future<Database> _init() async {
Database db = await openDatabase(
join(await getDatabasesPath(), 'activity.db'), //path
onCreate: (db, version) async {
await db.execute('''CREATE TABLE activity_table
(
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
)''');
},
version: 1,
);
}
editActivity({required Activity activity,}) async {
Database db = await database;
await db.update(
'activity_table',
activity.toMap(),
where: 'id = ?',
whereArgs: [
activity.id,
],
);
}
addActivity(Activity activity) async {
Database db = await database;
await db
.insert(
'activity_table',
activity.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
removeActivity(String id) async {
Database db = await database;
await db.delete(
'activity_table',
where: 'id = ?',
whereArgs: [id],
);
}
On every hot restart allActivity() is empty
allActivity() async {
Database db = await database;
List<Map<String, dynamic>> activitiesMapFromDB = await db.query('activity_table');
return activitiesMapFromDB;
}
}