I am currently successfully able to insert values into the system, however, I want to be able to display the inserted values in my console.
How do I print the inserted values in my console? I tried doing so and I was only able to get the "id" of the inserted value. I'm not sure how to print the rest of the values in the table.
Here's my insert code:
// Insert Operation: Insert a Note object to database
Future<int> insertNote(Note note) async {
//getting db reference
Database db = await database;
//running the insert command
//our data from note is converted to map object
var result = await db.insert(noteTable, note.toMap());
if (kDebugMode) {
print('Note data inserted successfully: $result');
}
return result;
}
Here's the code I used to convert the Note object into a Map object
// Convert a Note object into a Map object
Map<String, dynamic> toMap() {
var map = <String,dynamic>{};
if (id != null) {
map['id'] = _id;
}
map['title'] = _title;
map['description'] = _description;
map['priority'] = _priority;
map['color'] = _color;
map['date'] = _date;
return map;
}
This is the result on my console:
When you insert row in database you will only get row id in return.
So if you want to print recent data then you have to make a query to your database with id or you can also print all the data available.
For table
db.query("table_name);
or
db.rawQuery('SELECT * FROM "table"');
For specific id
db.query("table_name",where: '$rowId = ?', whereArgs: [id]);
or
db.rawQuery('SELECT * FROM "table" WHERE $rowId = $id');
For more info check : https://pub.dev/packages/sqflite
Related
I hope you can help me with getting a return value out of a future function.
I created a local MariaDB and connect to it with the mysql1 package. The next step is to get a value whenever a table is empty or not (indicates as 0 or 1). I archive that behavior with the following SQL query SELECT EXISTS (SELECT 1 FROM table);
Function to create a db connection.
//creates connection to local database. (used in .this((conn){}) function)
Future<MySqlConnection> getConnection() async {
var settings = ConnectionSettings(
host: host!,
port: port!,
user: user,
password: password,
db: db,
);
return await MySqlConnection.connect(settings);
}
My Function that should return 0 or 1, let me explan the code block down below.
getConnection() create database connection
trigger .then() to work with the output as conn
execute SQL query
format SQL query to just 0 or 1
Missing: should return the value when checkIfTableIsEmpty() is called
//should return 0 or 1 depending if table is empty or not.
checkIfTableIsEmpty(String table) async {
//holds the sql query that should get executed.
String sql = 'SELECT EXISTS (SELECT 1 FROM $table);';
//this should get returned after annitialised.
String? globalNumber;
//!!! creates the value 0 or 1 !!!
await getConnection().then( // (1)
(conn) async { // (2)
//output: result = (Fields: {EXISTS (SELECT 1 FROM master_key): 1})
Results result = await conn.query(sql); //(3)
String? number;
for (var row in result) {. // (4) <---- format output to just 0 or 1
number = '${row[0]}';
}
globalNumber = number;
print('$globalNumber'); // <---- output is 1
return globalNumber;
});
// (5) globalNumber should get printed
print('$globalNumber'); // <---- output null, this should be 1
}
Function that is currently returning null but should get value of globalNumber var.
//call the function and print result.
void testFunction() async {
print(checkIfTableIsEmpty('master_key'));
}
Hello i found the solution for my problem. I had to await on the result and delete the .then() function to avoid having callbacks. (See the comment of #Almis).
Thanks #Almis for the code improvement.
This is my final function that return 0 or 1.
checkIfTableIsEmpty(String table) async {
String sql = 'SELECT EXISTS (SELECT 1 FROM $table);';
String? globalNumber;
var conn = await getConnection();
Results result = await conn.query(sql);
for (var row in result) {
globalNumber = '${row[0]}';
}
return globalNumber;
}
void testFunction() async {
var x = await checkIfTableIsEmpty('master_key');
print(x);
}
Is there an automatic way to generate sqflite create table queries according to json data?
I m building Erp apps.So, i have to deal with 40-50 tables each time and
i think there should be an automatic way to do it like json to dart.
{
"sto_code": "120.001",
"sto_name": "NORMAL STOK",
"sto_amount": 1
}
No package that I know of does that yet. But you could use this code snippet to generate a CREATE TABLE statement with an example json file.
String getType(Type type){
if(type is int){
return 'INTEGER';
}else if(type is String){
return 'TEXT';
}else if(type is double){
return 'REAL';
}else{
return 'TEXT';
}
}
String createColumns(Map<dynamic, dynamic> map){
String columns = '';
map.forEach((key, value){
columns += '$key ${getType(value.runtimeType)}, ';
});
return columns.endsWith(', ') ? columns.substring(0,columns.length - 2) : columns;
}
String createTable(String tableName, Map<dynamic, dynamic> map){
String columns = createColumns(map);
String table = 'CREATE TABLE $tableName ($columns)';
return table;
}
I am trying to fetch all the conferences that contain current user's uid. I am trying to accomplish it by using OrderByChild($string).(firebaseauth.currentuser.uid) as show below in my codes. In my codes, i fetched the current users specific key in string and then used it to fetch all the data that contain that key.
String MyAssigningID = "...";
Future<void> _fetchUserASSIGNINGIDFromDatabase() async {
DatabaseReference reference = FirebaseDatabase.instance.reference().child("User").child(widget.GroupID).child("Group-Members").child(auth.currentUser.uid);
final DataSnapshot data = await reference.once();
setState(() {
MyAssigningID = data.value['AssigningID'].toString();
});
}
GetGroupFunction() {
DatabaseReference referenceData = FirebaseDatabase.instance.reference().child("User").child(widget.GroupID).child("Conferences");
referenceData.orderByChild(MyAssigningID).equalTo(auth.currentUser.uid).once().then((DataSnapshot dataSnapshot) {
Conferencelists.clear();
var keys = dataSnapshot.value.keys;
var values = dataSnapshot.value;
for (var key in keys) {
Conferencemodals conferencemodals = new Conferencemodals
(
values [key]['Title'],
values [key]['Description'],
values [key]['StartingTime'],
values [key]['EndingTime'],
values [key]['Duration'],
values [key]['ConferenceID'],
values [key]['SchoolUpin'],
values [key]['CreatedDate'],
values [key]['Published'],
values [key]['ConferenceDay'],
values [key]['ConferenceHost'],
);
Conferencelists.add(conferencemodals);
}
setState(() {
TotalConferences = Conferencelists.length.toString();
});
});
}
I have a JSON having some data as an array , and I wanna add
new data to JSON
This is My JSON structure
```[
{
"id":"JKT020",
"origin_time":"2020-06-30 12:00",
"location":"Jakarta, ID"
}
]```
I want to add new data so it can be like this
```[
{
"id":"JKT020",
"origin_time":"2020-06-30 12:00",
"location":"Jakarta, ID",
"flag":1
}
]```
Is it possible ? If it is can anyone tell me how to do that ? Thanks in advance.
And this is what I've been doing so far..
List data = json.decode(response.body);
for (int i = 0; i < data.length; i++) {
data.add(data[i]["flag"]=1);
print("object : " + data[i].toString());
}
});
It was printed like I want it, but return error in add line
The error said NoSuchMethodError: Class 'String' has no instance method '[]='
First of all, you have to Decode the JSON
var data=json.decode("Your JSON")
Now this is available as a list and map so you can add fields like
data[key]=value;
after that, you have to Encode it using json.encode
var data1=json.encode(data);
`
It's a good idea to get the JSON formatted and mapped to a Model. This will not only help to do null checks but also increase the readability of your code.
You can use a simple Model like
class myModel {
String id;
String originTime;
String location;
int flag;
myModel({this.id, this.originTime, this.location, this.flag});
myModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
originTime = json['origin_time'];
location = json['location'];
flag = json['flag'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['origin_time'] = this.originTime;
data['location'] = this.location;
data['flag'] = this.flag;
return data;
}
}
I’m using some sqflite to do a query on a database, and extract a specific name of a table, for example: I have 3 names, Roberto, Ricardo and Andres, and I want to obtain only the name of Roberto, so this is what im doing:
loginLogic() async {
var X = 'Roberto';
final db = await database;
List<Map> result = await db.rawQuery('SELECT * FROM Usuario WHERE username=?', [X]);
So now, I want to compare this result with another one to do an "if" function, just like this:
if(result==X){
return 1;
} else {
return 0;
}
But this is what flutter says:
List<Map<dynamic, dynamic>> result
Equality operator '==' invocation with references of unrelated
And the Debug console:
type 'Future<dynamic>' is not a subtype of type 'int'
So I need a way to compare the value that results from the list of users with the string with the variable I declarated 'X'.
Try using the reference of this problem
This is what I’ve tried:
loginLogicpar() async {
var X = 'Giova';
final db = await database;
final result = await db.rawQuery('SELECT * FROM Usuario WHERE username=?', [X]);
return result;
}
loginLogic() async {
var X = 'Giova';
final user = await loginLogicpar();
if(user==X){
return 1;
}
return 0;
}
And returns the exact same result: type 'Future' is not a subtype of type 'int'
Added the code so you can replicate it, just be sure you have sqflite on your depenencies.
It was a hell of a road, but i made it with the help of you all, but the final piece was #mutantkeyboard, what i was getting was a list of the different elements from the table of Sqflite, but after converting it with a variable and the .first function i get to transform it to another variables! here's what i made:
loginLogic() async {
final db = await database;
var table = await db.rawQuery("SELECT MAX(id)+1 as id FROM Usuario");
int id = table.last["id"];
for(var i=1; i<id; i++){
var result = await db.rawQuery('SELECT username FROM Usuario WHERE id=?', [i]);
String Y = result.first["username"];
if(Y=='Roberto'){
return 1;
}
}
return 0;
}
if you want to compare it with another variable outside, for example, an auth for a local-login (that's what i was doing, just for educational purpose, i'll NEVER suggest you to put your usernames and passwords inside your local software) and compare the textfield.text with the table, then you can modify the code to something like this:
loginLogic(String field) async {
final db = await database;
var table = await db.rawQuery("SELECT MAX(id)+1 as id FROM Usuario");
int id = table.last["id"];
for(var i=1; i<id; i++){
var result = await db.rawQuery('SELECT username FROM Usuario WHERE id=?', [i]);
String Y = result.first["username"];
if(Y==field){
return 1;
}
}
return 0;
}