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"
);
}
Related
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;
}
}
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.
I keep getting this syntax error : E/SQLiteLog( 4514): (1) near "null": syntax error in "CREATE TABLE expenses_table(id INTEGER PRIMARY KEY AUTOINCREMENT, null TEXT ,null TEXT)"
I am quite new to this, and have been using examples online to put this code together, but I can't seem to find what is causing this issue.
Any help would be very much appreciated!
'''
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'dart:async';
import 'expense_list.dart';
class ExpensesDatabase {
static ExpensesDatabase _expensesDatabase;
static Database _database;
String expensesTable = 'expenses_table';
String id = 'id';
String name;
String amount;
ExpensesDatabase._createInstance();
factory ExpensesDatabase() {
if (_expensesDatabase == null) {
_expensesDatabase = ExpensesDatabase._createInstance();
}
return _expensesDatabase;
}
Future<Database> get database async {
if (_database == null) {
_database = await initializeDatabase();
}
return _database;
}
Future<Database> initializeDatabase() async {
Directory directory = await getApplicationDocumentsDirectory();
String path = directory.path + 'expenses.db';
var expensesDatabase =
await openDatabase(path, version: 1, onCreate: _createDb);
return expensesDatabase;
}
void _createDb(Database db, int newVersion) async {
await db.execute(
'CREATE TABLE $expensesTable($id INTEGER PRIMARY KEY AUTOINCREMENT,'
'$name TEXT,'
'$amount TEXT)');
}
'''
Intialize your name and amount variables, its getting null because string name and amount are not initialised yet.
String name = 'name';
String amount = 'amount';
I have stored my phones call list into a data table. I want to store only new call list data into this data table. It means, only new data will be saved and existing data will be skipped.
Please tell me with example.
Here is my code:
this is the Database Helper
database_helper.dart
import 'dart:io';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
class DatabaseHelper {
static final _databaseName = "MyDatabase.db";
static final _databaseVersion = 1;
static final table = 'my_table';
static final columnId = '_id';
static final columnName = 'name';
static final columnNumber = 'number';
static final columnType = 'type';
static final columnDate = 'date';
static final columnDuration = 'duration';
// make this a singleton class
DatabaseHelper._privateConstructor();
static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
// only have a single app-wide reference to the database
static Database _database;
Future<Database> get database async {
if (_database != null) return _database;
// lazily instantiate the db the first time it is accessed
_database = await _initDatabase();
return _database;
}
// this opens the database (and creates it if it doesn't exist)
_initDatabase() async {
Directory documentsDirectory = await getExternalStorageDirectory();
String path = join(documentsDirectory.path, _databaseName);
await deleteDatabase(path);
return await openDatabase(path,
version: _databaseVersion, onCreate: _onCreate);
}
// SQL code to create the database table
Future _onCreate(Database db, int version) async {
await db.execute('''
CREATE TABLE $table (
$columnId INTEGER PRIMARY KEY,
$columnName TEXT,
$columnNumber INTEGER,
$columnType TEXT,
$columnDate DATETIME,
$columnDuration INTEGER
)
''');
}
// Helper methods
// Inserts a row in the database where each key in the Map is a column name
// and the value is the column value. The return value is the id of the
// inserted row.
Future<int> insert(Map<String, dynamic> row, {ConflictAlgorithm conflictAlgorithm = ConflictAlgorithm.replace}) async {
Database db = await instance.database;
return await db.insert(table, row, conflictAlgorithm: conflictAlgorithm);
}
// All of the rows are returned as a list of maps, where each map is
// a key-value list of columns.
Future<List<Map<String, dynamic>>> queryAllRows() async {
Database db = await instance.database;
return await db.query(table);
}
// All of the methods (insert, query, update, delete) can also be done using
// raw SQL commands. This method uses a raw query to give the row count.
Future<int> queryRowCount() async {
Database db = await instance.database;
return Sqflite.firstIntValue(
await db.rawQuery('SELECT COUNT(*) FROM $table'));
}
// We are assuming here that the id column in the map is set. The other
// column values will be used to update the row.
Future<int> update(Map<String, dynamic> row) async {
Database db = await instance.database;
int id = row[columnId];
return await db.update(table, row, where: '$columnId = ?', whereArgs: [id]);
}
// Deletes the row specified by the id. The number of affected rows is
// returned. This should be 1 as long as the row exists.
Future<int> delete(int id) async {
Database db = await instance.database;
return await db.delete(table, where: '$columnId = ?', whereArgs: [id]);
}
}
This is the main file. I have added here only the Database insertion method. home.dart
...
Future callLogDB() async {
Iterable<CallLogEntry> cLog = await CallLog.get();
final dbHelper = DatabaseHelper.instance;
cLog.forEach((log) async {
// row to insert
Map<String, dynamic> row = {
DatabaseHelper.columnName: '${log.name}',
DatabaseHelper.columnNumber: '${log.number}',
DatabaseHelper.columnType: '${log.callType}',
DatabaseHelper.columnDate:
'${DateTime.fromMillisecondsSinceEpoch(log.timestamp)}',
DatabaseHelper.columnDuration: '${log.duration}'
};
await dbHelper.insert(row, conflictAlgorithm: ConflictAlgorithm.replace);
print('CallLog:: $row');
});
return cLog;
}
...
What's the problem with my code?
there are several ways to do this, and the one I will offer are not the best or the nicest ones, but hope that they will help
1) Simply write all your data to table
You can just insert all your data to the table setting the ConflictAlgorithm to replace or ignore
db.insert(table, data, conflictAlgorithm: ConflictAlgorithm.replace);
This will replace/ignore same entries
2) Query, compare, replace
This is a less 'elegant' solution, you can first query all your data from table
db.query(table, columns: availableColumns, where: 'columnToQueryBy = ?', whereArgs: [neededValue]);
Then compare to the data you have
Then write using db.insert() as above
I think that in your case the first option suits better, this example pretty much covers most things that might help you
Hope it helps!
WHAT ABOUT Read Data from Sqflite and Show in datatable?
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]);
});
}
}