0
# Database Connections
1
2
Core connection functionality for establishing and managing database connections with flexible configuration options including SSL, timeouts, and authentication methods.
3
4
## Capabilities
5
6
### Create Connection
7
8
Creates a new database connection with the specified configuration.
9
10
```javascript { .api }
11
/**
12
* Creates a new database connection
13
* @param config - Connection configuration object or connection string
14
* @returns Connection instance
15
*/
16
function createConnection(config: ConnectionOptions | string): Connection;
17
```
18
19
**Usage Examples:**
20
21
```javascript
22
const mysql = require('mysql2');
23
24
// Using configuration object
25
const connection = mysql.createConnection({
26
host: 'localhost',
27
port: 3306,
28
user: 'root',
29
password: 'password',
30
database: 'testdb'
31
});
32
33
// Using connection string
34
const connection2 = mysql.createConnection('mysql://user:password@localhost:3306/database');
35
```
36
37
### Connection Class
38
39
Main connection class providing database interaction methods.
40
41
```typescript { .api }
42
interface Connection extends EventEmitter {
43
/** Connection configuration */
44
config: ConnectionOptions;
45
46
/** Current connection thread ID */
47
threadId: number;
48
49
/** Current connection state */
50
state: string;
51
52
/** Establish connection to database */
53
connect(callback?: (err: Error | null) => void): void;
54
55
/** Execute SQL query with optional parameters */
56
query(sql: string, callback?: QueryCallback): Query;
57
query(sql: string, values: any[], callback?: QueryCallback): Query;
58
query(options: QueryOptions, callback?: QueryCallback): Query;
59
60
/** Execute prepared statement with parameters */
61
execute(sql: string, values?: any[], callback?: ExecuteCallback): void;
62
63
/** Create prepared statement */
64
prepare(sql: string, callback?: (err: Error | null, statement?: PreparedStatement) => void): void;
65
66
/** Remove prepared statement */
67
unprepare(sql: string): void;
68
69
/** Begin database transaction */
70
beginTransaction(callback?: (err: Error | null) => void): void;
71
72
/** Commit current transaction */
73
commit(callback?: (err: Error | null) => void): void;
74
75
/** Rollback current transaction */
76
rollback(callback?: (err: Error | null) => void): void;
77
78
/** Change user authentication */
79
changeUser(options: ConnectionOptions, callback?: (err: Error | null) => void): void;
80
81
/** Ping server to keep connection alive */
82
ping(callback?: (err: Error | null) => void): void;
83
84
/** Close connection gracefully */
85
end(callback?: (err: Error | null) => void): void;
86
87
/** Force close connection immediately */
88
destroy(): void;
89
90
/** Pause connection data flow */
91
pause(): void;
92
93
/** Resume connection data flow */
94
resume(): void;
95
96
/** Escape SQL value to prevent injection */
97
escape(value: any): string;
98
99
/** Escape SQL identifier */
100
escapeId(value: string | string[]): string;
101
102
/** Format SQL query with values */
103
format(sql: string, values?: any[]): string;
104
}
105
```
106
107
### Connection Options
108
109
Configuration interface for database connections.
110
111
```typescript { .api }
112
interface ConnectionOptions {
113
/** Database server hostname */
114
host?: string;
115
116
/** Database server port number */
117
port?: number;
118
119
/** Local address for connection binding */
120
localAddress?: string;
121
122
/** Socket path for local connections */
123
socketPath?: string;
124
125
/** Database username */
126
user?: string;
127
128
/** Database password */
129
password?: string;
130
131
/** Database name to connect to */
132
database?: string;
133
134
/** Connection charset */
135
charset?: string;
136
137
/** Connection timezone */
138
timezone?: string;
139
140
/** Connection timeout in milliseconds */
141
connectTimeout?: number;
142
143
/** Query timeout in milliseconds */
144
acquireTimeout?: number;
145
146
/** Socket timeout in milliseconds */
147
timeout?: number;
148
149
/** SSL configuration */
150
ssl?: SslOptions | string;
151
152
/** Enable SQL_BIG_SELECTS */
153
bigNumberStrings?: boolean;
154
155
/** Return numbers as strings */
156
supportBigNumbers?: boolean;
157
158
/** Date strings instead of Date objects */
159
dateStrings?: boolean | string[];
160
161
/** Enable debug logging */
162
debug?: boolean | string[];
163
164
/** Trace SQL queries */
165
trace?: boolean;
166
167
/** Multiple statement support */
168
multipleStatements?: boolean;
169
170
/** Connection flags */
171
flags?: string | string[];
172
173
/** Custom type casting function */
174
typeCast?: boolean | ((field: FieldPacket, next: () => void) => any);
175
176
/** Maximum packet size */
177
maxPacketSize?: number;
178
179
/** Character set number */
180
charsetNumber?: number;
181
182
/** Compression support */
183
compress?: boolean;
184
185
/** Authentication plugin name */
186
authPlugins?: { [pluginName: string]: AuthPlugin };
187
188
/** Row format as array */
189
rowsAsArray?: boolean;
190
191
/** Named placeholders support */
192
namedPlaceholders?: boolean;
193
194
/** Nested tables support */
195
nestTables?: boolean | string;
196
197
/** Insert ID as string */
198
insertIdAsNumber?: boolean;
199
200
/** Decimal number handling */
201
decimalNumbers?: boolean;
202
203
/** Promise implementation */
204
Promise?: any;
205
206
/** Connection URI */
207
uri?: string;
208
}
209
```
210
211
### SSL Options
212
213
SSL/TLS configuration for secure connections.
214
215
```typescript { .api }
216
interface SslOptions {
217
/** Private key */
218
key?: string | string[] | Buffer | Buffer[];
219
220
/** Certificate */
221
cert?: string | string[] | Buffer | Buffer[];
222
223
/** Certificate authority */
224
ca?: string | string[] | Buffer | Buffer[];
225
226
/** Certificate revocation list */
227
crl?: string | string[] | Buffer | Buffer[];
228
229
/** Cipher suites */
230
ciphers?: string;
231
232
/** Private key passphrase */
233
passphrase?: string;
234
235
/** Reject unauthorized certificates */
236
rejectUnauthorized?: boolean;
237
238
/** Server name for SNI */
239
servername?: string;
240
241
/** Minimum TLS version */
242
minVersion?: string;
243
244
/** Maximum TLS version */
245
maxVersion?: string;
246
}
247
```
248
249
### Connection Events
250
251
Connections emit various events during their lifecycle.
252
253
```javascript { .api }
254
// Event: 'connect' - Connection established
255
connection.on('connect', () => {
256
console.log('Connected to database');
257
});
258
259
// Event: 'error' - Connection error occurred
260
connection.on('error', (error) => {
261
console.error('Connection error:', error);
262
});
263
264
// Event: 'end' - Connection ended
265
connection.on('end', () => {
266
console.log('Connection ended');
267
});
268
269
// Event: 'timeout' - Connection timeout
270
connection.on('timeout', () => {
271
console.log('Connection timeout');
272
});
273
```
274
275
### Connection Aliases
276
277
Additional functions that create connections.
278
279
```javascript { .api }
280
/**
281
* Alias for createConnection()
282
*/
283
const connect = createConnection;
284
```
285
286
## Error Handling
287
288
Connection operations can throw various types of errors:
289
290
```javascript
291
connection.connect((err) => {
292
if (err) {
293
console.error('Connection failed:', err.code, err.errno, err.sqlState);
294
return;
295
}
296
console.log('Connected successfully');
297
});
298
```
299
300
Common error codes include:
301
- `ER_ACCESS_DENIED_ERROR`: Authentication failed
302
- `ER_BAD_HOST_ERROR`: Unknown host
303
- `ECONNREFUSED`: Connection refused
304
- `PROTOCOL_CONNECTION_LOST`: Connection lost during operation