mysql1: ^0.20.0
[//]: # (create a function add host which in this case is localhost and port which your mySQL port is running)
[//]: # ( In case of Window you need XAMPP and in case of macOS see the documentation)
[//]: # (user is whatever the username you use to login into phpmyAdmin or your mySQL database user name or password)
[//]: # (db is database name you generated inside mySQL)
Future<void> connectDatabase() async {
final connect = await MySqlConnection.connect(ConnectionSettings(
host: '127.0.0.1',
port: 8080,
user: 'root',
db: 'task_managment',
));
// Create a table
await connect.query(
'CREATE TABLE task (id int NOT NULL AUTO_INCREMENT PRIMARY KEY, name varchar(255), email varchar(255), age int)');
// Insert some data
var result = await connect.query(
'insert into users (name, email, age) values (?, ?, ?)',
['Bob', '[email protected]', 25]);
print('Inserted row id=${result.insertId}');
// Query the database using a parameterized query
var results = await connect.query(
'select name, email, age from task where id = ?', [result.insertId]);
for (var row in results) {
print('Name: ${row[0]}, email: ${row[1]} age: ${row[2]}');
}
// Update some data
await connect.query('update users set age=? where name=?', [26, 'Bob']);
// Query again database using a parameterized query
var results2 = await connect.query(
'select name, email, age from users where id = ?', [result.insertId]);
for (var row in results2) {
print('Name: ${row[0]}, email: ${row[1]} age: ${row[2]}');
}
// Finally, close the connection
await connect.close();
}
When you are using this plugin, and you're adding the db name in connection setting if you are adding the same name it will give you error even if your data is getting insert inside the database of existing table but one thing you should remember that db name should be different because db represent the database name and table is that will be generated inside the database. One thing also that you should not write insert query again and again to insert multiple data. Just use the same query and change data inside, it will insert on top of it with different ID of course. And at the end, don't forget to close it.