Last active
December 23, 2015 18:29
-
-
Save PedersenThomas/6676458 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
import 'package:postgresql/postgresql.dart'; | |
void main() { | |
var username = "TheRightMan"; | |
var password = "WithTheRightSecret"; | |
var DBname = "AtTheRightPlace"; | |
var uri = 'postgres://$username:$password@localhost:5432/$DBname'; | |
connect(uri) | |
.then((Connection connection) => | |
insertPersonStored(connection, "Thomas", "Pedersen", new DateTime(1988, 9, 23), 1.80)) | |
.then((Connection connection) => | |
insertPersonPrepared(connection, "Donald", "Duck", new DateTime(1934, 2, 13), 1.31)) | |
.then((connection) => | |
printEntireTable(connection)) | |
.then((connection) => | |
connection.close()) | |
.catchError((e) => | |
print("Error: $e")); | |
} | |
Future insertPersonStored(Connection connection, String firstname, String lastname, DateTime dateOfBirth, double height) { | |
final String query = "SELECT insertperson('$firstname', '$lastname', '$dateOfBirth', $height);"; | |
return connection.query(query).listen((row) { | |
print("Inserted: (${row[0]}) $firstname $lastname, $dateOfBirth, $height"); | |
}).asFuture(connection); | |
} | |
Future insertPersonPrepared(Connection connection, String firstname, String lastname, DateTime dateOfBirth, double height) { | |
final String query = | |
'insert into person(firstname, lastname, dateOfBirth, height)'+ | |
' values (@firstname, @lastname, @dateOfBirth, @height);'; | |
return connection.execute(query, | |
{'firstname' : firstname, | |
'lastname' : lastname, | |
'dateOfBirth': dateOfBirth, | |
'height' : height}) | |
.then((rowsAffected) { | |
print("rowsAffected: $rowsAffected"); | |
return connection; | |
} | |
); | |
} | |
Future printEntireTable(Connection connection) { | |
final String query = "SELECT id, firstname, lastname, dateofbirth, height FROM person;"; | |
return connection.query(query).listen((row) { | |
var age = ((new DateTime.now()).difference(row.dateofbirth).inDays/365.2425).floor(); | |
print("(${row.id}) ${row.firstname} ${row.lastname} - $age years old - ${row.height}m"); | |
}).asFuture(connection); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment