]> begriffs open source - ai-pg/blob - full-docs/txt/ecpg-connect.txt
Convert HTML docs to more streamlined TXT
[ai-pg] / full-docs / txt / ecpg-connect.txt
1
2 34.2. Managing Database Connections #
3
4    34.2.1. Connecting to the Database Server
5    34.2.2. Choosing a Connection
6    34.2.3. Closing a Connection
7
8    This section describes how to open, close, and switch database
9    connections.
10
11 34.2.1. Connecting to the Database Server #
12
13    One connects to a database using the following statement:
14 EXEC SQL CONNECT TO target [AS connection-name] [USER user-name];
15
16    The target can be specified in the following ways:
17      * dbname[@hostname][:port]
18      * tcp:postgresql://hostname[:port][/dbname][?options]
19      * unix:postgresql://localhost[:port][/dbname][?options]
20      * an SQL string literal containing one of the above forms
21      * a reference to a character variable containing one of the above
22        forms (see examples)
23      * DEFAULT
24
25    The connection target DEFAULT initiates a connection to the default
26    database under the default user name. No separate user name or
27    connection name can be specified in that case.
28
29    If you specify the connection target directly (that is, not as a string
30    literal or variable reference), then the components of the target are
31    passed through normal SQL parsing; this means that, for example, the
32    hostname must look like one or more SQL identifiers separated by dots,
33    and those identifiers will be case-folded unless double-quoted. Values
34    of any options must be SQL identifiers, integers, or variable
35    references. Of course, you can put nearly anything into an SQL
36    identifier by double-quoting it. In practice, it is probably less
37    error-prone to use a (single-quoted) string literal or a variable
38    reference than to write the connection target directly.
39
40    There are also different ways to specify the user name:
41      * username
42      * username/password
43      * username IDENTIFIED BY password
44      * username USING password
45
46    As above, the parameters username and password can be an SQL
47    identifier, an SQL string literal, or a reference to a character
48    variable.
49
50    If the connection target includes any options, those consist of
51    keyword=value specifications separated by ampersands (&). The allowed
52    key words are the same ones recognized by libpq (see Section 32.1.2).
53    Spaces are ignored before any keyword or value, though not within or
54    after one. Note that there is no way to write & within a value.
55
56    Notice that when specifying a socket connection (with the unix:
57    prefix), the host name must be exactly localhost. To select a
58    non-default socket directory, write the directory's pathname as the
59    value of a host option in the options part of the target.
60
61    The connection-name is used to handle multiple connections in one
62    program. It can be omitted if a program uses only one connection. The
63    most recently opened connection becomes the current connection, which
64    is used by default when an SQL statement is to be executed (see later
65    in this chapter).
66
67    Here are some examples of CONNECT statements:
68 EXEC SQL CONNECT TO mydb@sql.mydomain.com;
69
70 EXEC SQL CONNECT TO tcp:postgresql://sql.mydomain.com/mydb AS myconnection USER
71 john;
72
73 EXEC SQL BEGIN DECLARE SECTION;
74 const char *target = "mydb@sql.mydomain.com";
75 const char *user = "john";
76 const char *passwd = "secret";
77 EXEC SQL END DECLARE SECTION;
78  ...
79 EXEC SQL CONNECT TO :target USER :user USING :passwd;
80 /* or EXEC SQL CONNECT TO :target USER :user/:passwd; */
81
82    The last example makes use of the feature referred to above as
83    character variable references. You will see in later sections how C
84    variables can be used in SQL statements when you prefix them with a
85    colon.
86
87    Be advised that the format of the connection target is not specified in
88    the SQL standard. So if you want to develop portable applications, you
89    might want to use something based on the last example above to
90    encapsulate the connection target string somewhere.
91
92    If untrusted users have access to a database that has not adopted a
93    secure schema usage pattern, begin each session by removing
94    publicly-writable schemas from search_path. For example, add options=-c
95    search_path= to options, or issue EXEC SQL SELECT
96    pg_catalog.set_config('search_path', '', false); after connecting. This
97    consideration is not specific to ECPG; it applies to every interface
98    for executing arbitrary SQL commands.
99
100 34.2.2. Choosing a Connection #
101
102    SQL statements in embedded SQL programs are by default executed on the
103    current connection, that is, the most recently opened one. If an
104    application needs to manage multiple connections, then there are three
105    ways to handle this.
106
107    The first option is to explicitly choose a connection for each SQL
108    statement, for example:
109 EXEC SQL AT connection-name SELECT ...;
110
111    This option is particularly suitable if the application needs to use
112    several connections in mixed order.
113
114    If your application uses multiple threads of execution, they cannot
115    share a connection concurrently. You must either explicitly control
116    access to the connection (using mutexes) or use a connection for each
117    thread.
118
119    The second option is to execute a statement to switch the current
120    connection. That statement is:
121 EXEC SQL SET CONNECTION connection-name;
122
123    This option is particularly convenient if many statements are to be
124    executed on the same connection.
125
126    Here is an example program managing multiple database connections:
127 #include <stdio.h>
128
129 EXEC SQL BEGIN DECLARE SECTION;
130     char dbname[1024];
131 EXEC SQL END DECLARE SECTION;
132
133 int
134 main()
135 {
136     EXEC SQL CONNECT TO testdb1 AS con1 USER testuser;
137     EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL CO
138 MMIT;
139     EXEC SQL CONNECT TO testdb2 AS con2 USER testuser;
140     EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL CO
141 MMIT;
142     EXEC SQL CONNECT TO testdb3 AS con3 USER testuser;
143     EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL CO
144 MMIT;
145
146     /* This query would be executed in the last opened database "testdb3". */
147     EXEC SQL SELECT current_database() INTO :dbname;
148     printf("current=%s (should be testdb3)\n", dbname);
149
150     /* Using "AT" to run a query in "testdb2" */
151     EXEC SQL AT con2 SELECT current_database() INTO :dbname;
152     printf("current=%s (should be testdb2)\n", dbname);
153
154     /* Switch the current connection to "testdb1". */
155     EXEC SQL SET CONNECTION con1;
156
157     EXEC SQL SELECT current_database() INTO :dbname;
158     printf("current=%s (should be testdb1)\n", dbname);
159
160     EXEC SQL DISCONNECT ALL;
161     return 0;
162 }
163
164    This example would produce this output:
165 current=testdb3 (should be testdb3)
166 current=testdb2 (should be testdb2)
167 current=testdb1 (should be testdb1)
168
169    The third option is to declare an SQL identifier linked to the
170    connection, for example:
171 EXEC SQL AT connection-name DECLARE statement-name STATEMENT;
172 EXEC SQL PREPARE statement-name FROM :dyn-string;
173
174    Once you link an SQL identifier to a connection, you execute dynamic
175    SQL without an AT clause. Note that this option behaves like
176    preprocessor directives, therefore the link is enabled only in the
177    file.
178
179    Here is an example program using this option:
180 #include <stdio.h>
181
182 EXEC SQL BEGIN DECLARE SECTION;
183 char dbname[128];
184 char *dyn_sql = "SELECT current_database()";
185 EXEC SQL END DECLARE SECTION;
186
187 int main(){
188   EXEC SQL CONNECT TO postgres AS con1;
189   EXEC SQL CONNECT TO testdb AS con2;
190   EXEC SQL AT con1 DECLARE stmt STATEMENT;
191   EXEC SQL PREPARE stmt FROM :dyn_sql;
192   EXEC SQL EXECUTE stmt INTO :dbname;
193   printf("%s\n", dbname);
194
195   EXEC SQL DISCONNECT ALL;
196   return 0;
197 }
198
199    This example would produce this output, even if the default connection
200    is testdb:
201 postgres
202
203 34.2.3. Closing a Connection #
204
205    To close a connection, use the following statement:
206 EXEC SQL DISCONNECT [connection];
207
208    The connection can be specified in the following ways:
209      * connection-name
210      * CURRENT
211      * ALL
212
213    If no connection name is specified, the current connection is closed.
214
215    It is good style that an application always explicitly disconnect from
216    every connection it opened.