1
+ /// Example for the `postgres` package.
2
+ ///
3
+ /// Running the example requires access to a postgres server. If you have docker
4
+ /// installed, you can start a postgres server to run this example with
5
+ ///
6
+ /// ```
7
+ /// docker run --detach --name postgres_for_dart_test -p 127.0.0.1:5432:5432 -e POSTGRES_USER=user -e POSTGRES_DATABASE=database -e POSTGRES_PASSWORD=pass postgres
8
+ /// ```
9
+ ///
10
+ /// To stop and clear the database server once you're done testing, run
11
+ ///
12
+ /// ```
13
+ /// docker container rm --force postgres_for_dart_test
14
+ /// ```
15
+ library ;
16
+
1
17
import 'package:postgres/postgres.dart' ;
2
18
3
19
void main () async {
4
- final conn = await Connection .open (Endpoint (
5
- host: 'localhost' ,
6
- database: 'postgres' ,
7
- username: 'user' ,
8
- password: 'pass' ,
9
- ));
20
+ final conn = await Connection .open (
21
+ Endpoint (
22
+ host: 'localhost' ,
23
+ database: 'postgres' ,
24
+ username: 'user' ,
25
+ password: 'pass' ,
26
+ ),
27
+ // The postgres server hosted locally doesn't have SSL by default. If you're
28
+ // accessing a postgres server over the Internet, the server should support
29
+ // SSL and you should swap out the mode with `SslMode.verifyFull`.
30
+ settings: ConnectionSettings (sslMode: SslMode .disable),
31
+ );
10
32
print ('has connection!' );
11
33
34
+ // Simple query without results
35
+ await conn.execute ('CREATE TABLE IF NOT EXISTS a_table ('
36
+ ' id TEXT NOT NULL, '
37
+ ' totals INTEGER NOT NULL DEFAULT 0'
38
+ ')' );
39
+
12
40
// simple query
13
41
final result0 = await conn.execute ("SELECT 'foo'" );
14
42
print (result0[0 ][0 ]); // first row, first column
15
43
16
- // name parameter query
44
+ // Using prepared statements to supply values
17
45
final result1 = await conn.execute (
46
+ r'INSERT INTO a_table (id) VALUES ($1)' ,
47
+ parameters: ['example row' ],
48
+ );
49
+ print ('Inserted ${result1 .affectedRows } rows' );
50
+
51
+ // name parameter query
52
+ final result2 = await conn.execute (
18
53
Sql .named ('SELECT * FROM a_table WHERE id=@id' ),
19
- parameters: {'id' : 'xyz ' },
54
+ parameters: {'id' : 'example row ' },
20
55
);
21
- print (result1 .first.toColumnMap ());
56
+ print (result2 .first.toColumnMap ());
22
57
23
58
// transaction
24
59
await conn.runTx ((s) async {
25
- final rs = await s.execute ('SELECT count(*) FROM foo ' );
60
+ final rs = await s.execute ('SELECT count(*) FROM a_table ' );
26
61
await s.execute (
27
62
r'UPDATE a_table SET totals=$1 WHERE id=$2' ,
28
63
parameters: [rs[0 ][0 ], 'xyz' ],
@@ -31,8 +66,8 @@ void main() async {
31
66
32
67
// prepared statement
33
68
final statement = await conn.prepare (Sql ("SELECT 'foo';" ));
34
- final result2 = await statement.run ([]);
35
- print (result2 );
69
+ final result3 = await statement.run ([]);
70
+ print (result3 );
36
71
await statement.dispose ();
37
72
38
73
// preared statement with types
0 commit comments