Fast MySQL client for Node.js with support for prepared statements, SSL, compression, and promise-based APIs
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Core connection functionality for establishing and managing database connections with flexible configuration options including SSL, timeouts, and authentication methods.
Creates a new database connection with the specified configuration.
/**
* Creates a new database connection
* @param config - Connection configuration object or connection string
* @returns Connection instance
*/
function createConnection(config: ConnectionOptions | string): Connection;Usage Examples:
const mysql = require('mysql2');
// Using configuration object
const connection = mysql.createConnection({
host: 'localhost',
port: 3306,
user: 'root',
password: 'password',
database: 'testdb'
});
// Using connection string
const connection2 = mysql.createConnection('mysql://user:password@localhost:3306/database');Main connection class providing database interaction methods.
interface Connection extends EventEmitter {
/** Connection configuration */
config: ConnectionOptions;
/** Current connection thread ID */
threadId: number;
/** Current connection state */
state: string;
/** Establish connection to database */
connect(callback?: (err: Error | null) => void): void;
/** Execute SQL query with optional parameters */
query(sql: string, callback?: QueryCallback): Query;
query(sql: string, values: any[], callback?: QueryCallback): Query;
query(options: QueryOptions, callback?: QueryCallback): Query;
/** Execute prepared statement with parameters */
execute(sql: string, values?: any[], callback?: ExecuteCallback): void;
/** Create prepared statement */
prepare(sql: string, callback?: (err: Error | null, statement?: PreparedStatement) => void): void;
/** Remove prepared statement */
unprepare(sql: string): void;
/** Begin database transaction */
beginTransaction(callback?: (err: Error | null) => void): void;
/** Commit current transaction */
commit(callback?: (err: Error | null) => void): void;
/** Rollback current transaction */
rollback(callback?: (err: Error | null) => void): void;
/** Change user authentication */
changeUser(options: ConnectionOptions, callback?: (err: Error | null) => void): void;
/** Ping server to keep connection alive */
ping(callback?: (err: Error | null) => void): void;
/** Close connection gracefully */
end(callback?: (err: Error | null) => void): void;
/** Force close connection immediately */
destroy(): void;
/** Pause connection data flow */
pause(): void;
/** Resume connection data flow */
resume(): void;
/** Escape SQL value to prevent injection */
escape(value: any): string;
/** Escape SQL identifier */
escapeId(value: string | string[]): string;
/** Format SQL query with values */
format(sql: string, values?: any[]): string;
}Configuration interface for database connections.
interface ConnectionOptions {
/** Database server hostname */
host?: string;
/** Database server port number */
port?: number;
/** Local address for connection binding */
localAddress?: string;
/** Socket path for local connections */
socketPath?: string;
/** Database username */
user?: string;
/** Database password */
password?: string;
/** Database name to connect to */
database?: string;
/** Connection charset */
charset?: string;
/** Connection timezone */
timezone?: string;
/** Connection timeout in milliseconds */
connectTimeout?: number;
/** Query timeout in milliseconds */
acquireTimeout?: number;
/** Socket timeout in milliseconds */
timeout?: number;
/** SSL configuration */
ssl?: SslOptions | string;
/** Enable SQL_BIG_SELECTS */
bigNumberStrings?: boolean;
/** Return numbers as strings */
supportBigNumbers?: boolean;
/** Date strings instead of Date objects */
dateStrings?: boolean | string[];
/** Enable debug logging */
debug?: boolean | string[];
/** Trace SQL queries */
trace?: boolean;
/** Multiple statement support */
multipleStatements?: boolean;
/** Connection flags */
flags?: string | string[];
/** Custom type casting function */
typeCast?: boolean | ((field: FieldPacket, next: () => void) => any);
/** Maximum packet size */
maxPacketSize?: number;
/** Character set number */
charsetNumber?: number;
/** Compression support */
compress?: boolean;
/** Authentication plugin name */
authPlugins?: { [pluginName: string]: AuthPlugin };
/** Row format as array */
rowsAsArray?: boolean;
/** Named placeholders support */
namedPlaceholders?: boolean;
/** Nested tables support */
nestTables?: boolean | string;
/** Insert ID as string */
insertIdAsNumber?: boolean;
/** Decimal number handling */
decimalNumbers?: boolean;
/** Promise implementation */
Promise?: any;
/** Connection URI */
uri?: string;
}SSL/TLS configuration for secure connections.
interface SslOptions {
/** Private key */
key?: string | string[] | Buffer | Buffer[];
/** Certificate */
cert?: string | string[] | Buffer | Buffer[];
/** Certificate authority */
ca?: string | string[] | Buffer | Buffer[];
/** Certificate revocation list */
crl?: string | string[] | Buffer | Buffer[];
/** Cipher suites */
ciphers?: string;
/** Private key passphrase */
passphrase?: string;
/** Reject unauthorized certificates */
rejectUnauthorized?: boolean;
/** Server name for SNI */
servername?: string;
/** Minimum TLS version */
minVersion?: string;
/** Maximum TLS version */
maxVersion?: string;
}Connections emit various events during their lifecycle.
// Event: 'connect' - Connection established
connection.on('connect', () => {
console.log('Connected to database');
});
// Event: 'error' - Connection error occurred
connection.on('error', (error) => {
console.error('Connection error:', error);
});
// Event: 'end' - Connection ended
connection.on('end', () => {
console.log('Connection ended');
});
// Event: 'timeout' - Connection timeout
connection.on('timeout', () => {
console.log('Connection timeout');
});Additional functions that create connections.
/**
* Alias for createConnection()
*/
const connect = createConnection;Connection operations can throw various types of errors:
connection.connect((err) => {
if (err) {
console.error('Connection failed:', err.code, err.errno, err.sqlState);
return;
}
console.log('Connected successfully');
});Common error codes include:
ER_ACCESS_DENIED_ERROR: Authentication failedER_BAD_HOST_ERROR: Unknown hostECONNREFUSED: Connection refusedPROTOCOL_CONNECTION_LOST: Connection lost during operation