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

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;
}
}

Related

How to connect sqlite db flutter

I need the fix the problem when I put all information and click save > > there's nothing on the database
0
I need the fix the problem when I put all information and click save there's nothing on the database
Error:
E/flutter (12919): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: DatabaseException(table PERSON has no column named salary (code 1 SQLITE_ERROR): ,
Error:
E/flutter (12919): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: DatabaseException(table PERSON has no column named salary (code 1 SQLITE_ERROR):
enter image description here
litedb.dart:
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;
}
}
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;
}
}
I need help please?????
You will need to either add the "salary" column to the "PERSON" table in the SQLite database, or update your Flutter code to reference a different column name.
You can add a new column "salary" to an existing table "PERSON"
Future<void> addSalaryColumn() async {
final db = await database;
await db.execute(
"ALTER TABLE PERSON ADD COLUMN salary INTEGER DEFAULT 0"
);
}

id integer, auto increment, and PRIMARY KEY is null in database

I am creating database for todo application, i made id integer, auto increment, and PRIMARY KEY, But it stored on database null!
the stored database is:
I/flutter ( 2705): print all Data [{id: null, content: l will go
home, status: today, isFinished: false}, {id: null, content: buy tea,
status: today, isFinished: true}]
the code is:
class DBHelper {
DBHelper._();
factory DBHelper() => instance;
static final DBHelper instance = DBHelper._();
Database? _db;
Future<Database> _createDB() async {
if (_db != null) return _db!;
String path = join(await getDatabasesPath(), 'todo.db');
_db = await openDatabase(path, version: 1,
onCreate: (Database database, int version) {
return database.execute(
"CREATE TABLE tasks (id integer auto increment PRIMARY KEY ,content TEXT,status varchar(15),isFinished BOOLEAN) ");
}, onOpen: (_) {
print("\n opened \n ");
});
return _db!;
}
Future<int> insertNodeToDB(NoteDatabaseModel noteDatabaseModel) async {
Database _database = await _createDB();
return _database.rawInsert(
'INSERT INTO tasks (content,status,isFinished)values("${noteDatabaseModel.content}", "${noteDatabaseModel.status}","${noteDatabaseModel.isFinished}")');
}
}
You are just returning the data you inserted and not the row itself. You will need to run an inline select statement to return the row you inserted with it's generated id, something like this should work
Future<int> insertNodeToDB(NoteDatabaseModel noteDatabaseModel) async {
Database _database = await _createDB();
var result = _database.rawInsert(
'INSERT INTO tasks (content,status,isFinished)values("${noteDatabaseModel.content}", "${noteDatabaseModel.status}","${noteDatabaseModel.isFinished}"); SELECT * FROM tasks WHERE id = last_inserted_row_id();');
Return result;
}
last_inserted_rowid() is a function to return the last generated id.

Sqlflite - Null check operator used on a null value

I received - Null check operator used on a null value this error while trying to test my sqflite application. Even thought the code is working in emulator. but it didnt passed the test.
Kindly help.
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
class DbHelper {
static final DbHelper instance = DbHelper._instance();
DbHelper._instance();
static Database? _db;
Future<Database> get db async {
if (_db != null) return db;
_db = await _initDb();
return _db!;
}
Future<Database> _initDb() async {
Directory dir = await getApplicationDocumentsDirectory();
String path = dir.path + '/account_keeper.db';
final accountManagerDb = await openDatabase(
path,
version: 1,
onCreate: _createDb,
);
return accountManagerDb;
}
void _createDb(Database db, int version) async {
// Table 1- BusinessProfile Profile
print('creating db');
print('--create database--');
const String businessProfileTable = 'businessProfile_table';
String businessId = 'id';
String businessName = 'businessName';
await db.execute(
'''
CREATE TABLE
$businessProfileTable(
$businessId INTEGER PRIMARY KEY AUTOINCREMENT,
$businessName TEXTT )''',
);
}
}

Flutter does not run Async function

I am trying to get an async function _read() to run and the function does not pass the line:
Reading reading = await helper.queryReading(rowId); in this function:
_read() async {
DatabaseHelper helper = DatabaseHelper.instance;
int rowId = 1;
//lines above here executes
Reading reading = await helper.queryReading(rowId); //this is the line it stops on
// nothing below here is executed
if (reading == null) {
print('read row $rowId: empty');
} else {
print('read row $rowId: ${reading.reading}');
}
}
It is being called from the following function
class Profile {
Widget getScreen(){
print("Attempting to read db");
_read();
return Scaffold( ...)
Here is my helper class:
import 'dart:ffi';
import 'dart:io';
import 'package:ema/Readings.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
//table structure
final String tableName = 'Readings';
final String databasecolumnId = '_id';
final String databaseReading = 'Reading';
final String databaseDate = 'Time';
class DatabaseHelper {
//This is the name of the database file on disk
static final _databaseName = "readings.db";
//handles versioning for databases
static final _databaseVersion = 1;
//makes a singleton classs
DatabaseHelper._privateConstructor();
static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
//allows only one item to access the database
static Database _database;
Future<Database> get database async {
_database = await _initDatabase();
return database;
}
//this opens and creates the database
_initDatabase() async {
// The path_provider plugin gets the right directory for Android or iOS.
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, _databaseName);
// Open the database. Can also add an onUpdate callback parameter.
return await openDatabase(path,
version: _databaseVersion,
onCreate: _onCreate);
}
//Creates the database
Future _onCreate(Database db, int version) async {
await db.execute(
'''
CREATE TABLE $tableName (
$databasecolumnId INTEGER PRIMARY KEY,
$databaseReading REAL NOT NULL,
$databaseDate INTERGER NOT NULL
)
'''
);
}
Future<int> insertReading(Reading reading) async {
Database db = await database;
int id = await db.insert(tableName, reading.toMap());
return id;
}
//gets reading
Future<Reading> queryReading(int id) async {
print("queryReading"); //gets here
Database db = await database;
print("Getting Db"); // not actually getting here
List<Map> maps = await db.query(tableName,
columns: [databasecolumnId, databaseReading, databaseDate],
where: '$databasecolumnId = ?',
whereArgs: [id]);
if (maps.length > 0) {
return Reading.fromMap(maps.first);
}
print('maps length : ${maps.length}');
return null;
}
}
Here is my Readings class:
class Reading {
int id;
double reading;
DateTime date;
//constructor
Reading({this.id, this.reading, this.date});
Map<String, dynamic> toMap() {
var map = <String, dynamic>{
databaseReading: reading,
databaseDate: date.millisecondsSinceEpoch,
};
if (id != null) {
map[databasecolumnId] = id;
}
return map;
}
//extracts a node object from the map obect
Reading.fromMap(Map<String, dynamic> map) {
id = map[databasecolumnId];
reading = map[databaseReading];
date = new DateTime.fromMillisecondsSinceEpoch(map [databaseDate]);
}
}
Turns out there was a deadlock in getting the database. By putting a lock on it it worked.
Here is the code to resolve it:
///declreation of the database
Database _database;
///Gets the database ensuring that there are no locks currently on the database
Future<Database> get database async {
if (_database != null) return _database;
_database = await _initDatabase();
return _database;
}

Initialized database still returns as null [Flutter, sqflite]

I'm trying to perform CRUD operations on Flutter, using the sqflite library. Online resources point towards a bunch of ways to go about this. Here is my implementation:
class SqlManager {
static const String tname = 'table1';
static const String dname = 'database.db';
Future<Database> db;
initDB() async {
Directory path = await getApplicationDocumentsDirectory();
db = openDatabase(join(path.path, dname), version: 1, onCreate: (db, version) {
return db.execute(
'CREATE TABLE $tname (id INTEGER PRIMARY KEY, name TEXT, type TEXT, time1 INTEGER, time2 INTEGER, imp INTEGER, urg INTEGER)');
});
}
Future<void> writing(Task task) async {
print("called");
final Database DB = await db;
await DB.insert(
tname,
task.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
print("Execution completed");
}
Future<List<Task>> reading() async {
Database DB = await db;
List<Map<String, dynamic>> maps = await DB.query(tname);
return List.generate(maps.length, (i) {
return Task.fromMap(maps[i]);
});
}
}
Whenever I attempt to call any of these functions, I hit upon a NoSuchMethodError, thrown by the variable 'DB' inside one of these functions. Any help is appreciated, thanks!
Whenever I attempt to call any of these functions, I hit upon a NoSuchMethodError, thrown by the variable 'DB' inside one of these functions. Any help is appreciated, thanks!
It's because you haven't initialized your database by calling the initDB(). So, call it before you call the method using the database. But you'll end with recreating each instance for each call.
The better way is by creating a singleton for your database. Modify your SqlManager to something like this:
class SqlManager {
static const String tname = 'table1';
static const String dname = 'database.db';
// Future<Database> db;
// Make a singleton class
SqlManager._privateConstructor();
static final SqlManager instance = SqlManager._privateConstructor();
// Use a single reference to the db.
static Database _db;
// Use this getter to use the database.
Future<Database> get database async {
if (_db != null) return _database;
// Instantiate db the first time it is accessed
_db = await _initDB();
return _db;
}
// Init the database for the first time.
_initDB() async {
Directory path = await getApplicationDocumentsDirectory();
return await openDatabase(join(path.path, dname), version: 1, onCreate: (db, version) {
return db.execute(
'CREATE TABLE $tname (id INTEGER PRIMARY KEY, name TEXT, type TEXT, time1 INTEGER, time2 INTEGER, imp INTEGER, urg INTEGER)');
});
}
// Then you can use the database getter in another method
Future<List<Task>> reading() async {
Database DB = await instance.database;
List<Map<String, dynamic>> maps = await DB.query(tname);
return List.generate(maps.length, (i) {
return Task.fromMap(maps[i]);
});
}
}