or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

async.mdauth.mdconnection.mdconstants.mdcursors.mderrors.mdindex.mdpooling.mdtypes.mdutilities.md

connection.mddocs/

0

# Connection Management

1

2

Establish and manage database connections to MySQL servers with comprehensive configuration options, SSL/TLS support, and optional C extension optimization.

3

4

## Imports

5

6

```python { .api }

7

from typing import Any, Dict, List, Optional, Sequence, Tuple, Type, Union

8

from mysql.connector import MySQLConnection, PooledMySQLConnection

9

from mysql.connector.cursor import MySQLCursor

10

```

11

12

## Core Connection Functions

13

14

```python { .api }

15

def connect(**kwargs) -> Union[MySQLConnection, PooledMySQLConnection]:

16

"""

17

Create connection to MySQL server.

18

19

Returns PooledMySQLConnection when pool parameters are provided,

20

otherwise returns MySQLConnection or CMySQLConnection (if C extension available).

21

"""

22

pass

23

24

# Alias for connect function

25

Connect = connect

26

```

27

28

## Connection Classes

29

30

### MySQLConnection

31

32

```python { .api }

33

class MySQLConnection:

34

"""

35

Main synchronous connection class implementing DB-API 2.0.

36

Provides standard MySQL connectivity with transaction support.

37

"""

38

39

def __init__(self, **kwargs) -> None:

40

"""Initialize connection with configuration parameters."""

41

pass

42

43

def connect(self, **kwargs) -> None:

44

"""Establish connection to MySQL server."""

45

pass

46

47

def disconnect(self) -> None:

48

"""Close connection to MySQL server."""

49

pass

50

51

def close(self) -> None:

52

"""Close connection (alias for disconnect)."""

53

pass

54

55

def is_connected(self) -> bool:

56

"""Check if connection is active."""

57

pass

58

59

def ping(self, reconnect: bool = False, attempts: int = 1, delay: int = 0) -> None:

60

"""Test connection to server, optionally reconnecting."""

61

pass

62

63

def reconnect(self, attempts: int = 1, delay: int = 0) -> None:

64

"""Reconnect to MySQL server."""

65

pass

66

67

def cursor(self,

68

buffered: Optional[bool] = None,

69

raw: Optional[bool] = None,

70

prepared: Optional[bool] = None,

71

cursor_class: Optional[Type] = None,

72

dictionary: Optional[bool] = None,

73

named_tuple: Optional[bool] = None) -> MySQLCursor:

74

"""Create cursor for executing SQL statements."""

75

pass

76

77

def commit(self) -> None:

78

"""Commit current transaction."""

79

pass

80

81

def rollback(self) -> None:

82

"""Rollback current transaction."""

83

pass

84

85

def start_transaction(self,

86

consistent_snapshot: bool = False,

87

isolation_level: Optional[str] = None,

88

readonly: Optional[bool] = None) -> None:

89

"""Start new transaction with optional configuration."""

90

pass

91

92

@property

93

def autocommit(self) -> bool:

94

"""Get autocommit mode status."""

95

pass

96

97

@autocommit.setter

98

def autocommit(self, value: bool) -> None:

99

"""Set autocommit mode."""

100

pass

101

102

@property

103

def database(self) -> str:

104

"""Get current database name."""

105

pass

106

107

@database.setter

108

def database(self, value: str) -> None:

109

"""Change current database."""

110

pass

111

112

@property

113

def server_version(self) -> Tuple[int, int, int]:

114

"""Get MySQL server version tuple."""

115

pass

116

117

@property

118

def connection_id(self) -> int:

119

"""Get MySQL connection ID."""

120

pass

121

122

@property

123

def charset(self) -> str:

124

"""Get connection character set."""

125

pass

126

127

@charset.setter

128

def charset(self, value: str) -> None:

129

"""Set connection character set."""

130

pass

131

132

@property

133

def collation(self) -> str:

134

"""Get connection collation."""

135

pass

136

137

@collation.setter

138

def collation(self, value: str) -> None:

139

"""Set connection collation."""

140

pass

141

142

@property

143

def sql_mode(self) -> str:

144

"""Get SQL mode."""

145

pass

146

147

@sql_mode.setter

148

def sql_mode(self, value: str) -> None:

149

"""Set SQL mode."""

150

pass

151

152

@property

153

def time_zone(self) -> str:

154

"""Get connection time zone."""

155

pass

156

157

@time_zone.setter

158

def time_zone(self, value: str) -> None:

159

"""Set connection time zone."""

160

pass

161

162

def cmd_query(self, query: Union[str, bytes]) -> Dict:

163

"""Execute query and return raw result."""

164

pass

165

166

def cmd_quit(self) -> bytes:

167

"""Send quit command to server."""

168

pass

169

170

def cmd_init_db(self, database: str) -> bytes:

171

"""Send init_db command to change database."""

172

pass

173

174

def cmd_refresh(self, options: int) -> bytes:

175

"""Send refresh command with specified options."""

176

pass

177

178

def cmd_statistics(self) -> Dict:

179

"""Get server statistics."""

180

pass

181

182

def cmd_process_info(self) -> Tuple:

183

"""Get server process information."""

184

pass

185

186

def cmd_process_kill(self, mysql_pid: int) -> bytes:

187

"""Kill MySQL process by ID."""

188

pass

189

190

def cmd_debug(self) -> bytes:

191

"""Send debug command to server."""

192

pass

193

194

def cmd_ping(self) -> bytes:

195

"""Send ping command to server."""

196

pass

197

198

def cmd_change_user(self, username: str = '', password: str = '', database: str = '', charset: int = 33) -> bytes:

199

"""Change user authentication."""

200

pass

201

202

def cmd_stmt_prepare(self, statement: Union[str, bytes]) -> Dict:

203

"""Prepare SQL statement."""

204

pass

205

206

def cmd_stmt_execute(self, statement_id: int, data: Tuple = (), parameters: Tuple = (), flags: int = 0) -> Optional[Dict]:

207

"""Execute prepared statement."""

208

pass

209

210

def cmd_stmt_close(self, statement_id: int) -> bytes:

211

"""Close prepared statement."""

212

pass

213

214

def cmd_stmt_reset(self, statement_id: int) -> bytes:

215

"""Reset prepared statement."""

216

pass

217

218

def reset_session(self, user_variables: Optional[Dict] = None, session_variables: Optional[Dict] = None) -> None:

219

"""Reset session to initial state."""

220

pass

221

222

def get_warnings(self, count: Optional[int] = None) -> List[Tuple]:

223

"""Get warning messages from last statement."""

224

pass

225

226

@property

227

def warning_count(self) -> int:

228

"""Get warning count from last statement."""

229

pass

230

231

@property

232

def info_msg(self) -> Optional[str]:

233

"""Get info message from last statement."""

234

pass

235

236

@property

237

def field_count(self) -> int:

238

"""Get field count from last result."""

239

pass

240

241

@property

242

def insert_id(self) -> int:

243

"""Get auto-generated ID from last INSERT."""

244

pass

245

246

@property

247

def affected_rows(self) -> int:

248

"""Get affected row count from last statement."""

249

pass

250

251

@property

252

def in_transaction(self) -> bool:

253

"""Check if connection is in transaction."""

254

pass

255

256

# Query Attributes API

257

@property

258

def query_attrs(self) -> List[Tuple[str, Any]]:

259

"""Get query attributes list."""

260

pass

261

262

def query_attrs_append(self, value: Tuple[str, Any]) -> None:

263

"""

264

Add element to query attributes list.

265

266

If an element with the same name exists, it will be replaced.

267

"""

268

pass

269

270

def query_attrs_remove(self, name: str) -> Any:

271

"""

272

Remove element by name from query attributes list.

273

274

Returns the corresponding value if found, None otherwise.

275

"""

276

pass

277

278

def query_attrs_clear(self) -> None:

279

"""Clear all query attributes."""

280

pass

281

282

# Server Information API

283

def get_server_info(self) -> Optional[str]:

284

"""Get original MySQL server version information string."""

285

pass

286

287

def get_server_version(self) -> Optional[Tuple[int, ...]]:

288

"""Get MySQL server version as tuple of integers."""

289

pass

290

291

@property

292

def server_info(self) -> Optional[str]:

293

"""Get original MySQL server version information string."""

294

pass

295

296

# Security and State API

297

@property

298

def is_secure(self) -> bool:

299

"""Check if connection uses SSL/TLS or Unix socket security."""

300

pass

301

302

@property

303

def have_next_result(self) -> bool:

304

"""Check if there are additional result sets available."""

305

pass

306

307

def set_client_flags(self, flags: Union[int, Sequence[int]]) -> int:

308

"""

309

Set client capability flags.

310

311

Args:

312

flags: Integer or sequence of ClientFlag values

313

314

Returns:

315

Current client flags value

316

"""

317

pass

318

319

def get_self(self) -> 'MySQLConnection':

320

"""Return self for weakref.proxy support."""

321

pass

322

323

def __enter__(self) -> 'MySQLConnection':

324

"""Context manager entry."""

325

pass

326

327

def __exit__(self, exc_type, exc_val, exc_tb) -> None:

328

"""Context manager exit with automatic cleanup."""

329

pass

330

```

331

332

### CMySQLConnection

333

334

```python { .api }

335

class CMySQLConnection(MySQLConnection):

336

"""

337

C Extension optimized connection class.

338

Available when C extension is installed and HAVE_CEXT is True.

339

Provides same interface as MySQLConnection with improved performance.

340

"""

341

pass

342

```

343

344

## Connection Parameters

345

346

### Basic Parameters

347

348

```python { .api }

349

# Essential connection parameters

350

connection_config = {

351

'host': str, # MySQL server host (default: 'localhost')

352

'port': int, # MySQL server port (default: 3306)

353

'user': str, # Username for authentication

354

'password': str, # Password for authentication

355

'database': str, # Database name to connect to

356

'unix_socket': str, # Unix socket path (alternative to host/port)

357

}

358

```

359

360

### Character Set and Encoding

361

362

```python { .api }

363

charset_config = {

364

'charset': str, # Connection character set (default: 'utf8mb4')

365

'collation': str, # Connection collation

366

'use_unicode': bool, # Enable Unicode support (default: True)

367

}

368

```

369

370

### Connection Behavior

371

372

```python { .api }

373

behavior_config = {

374

'autocommit': bool, # Enable autocommit mode (default: False)

375

'time_zone': str, # Connection time zone

376

'sql_mode': str, # SQL mode settings

377

'init_command': str, # Command to run on connect

378

'connect_timeout': int, # Connection timeout in seconds (default: 10)

379

'read_timeout': int, # Read timeout in seconds

380

'write_timeout': int, # Write timeout in seconds

381

'client_flags': List[int], # MySQL client flags

382

'compress': bool, # Enable compression (default: False)

383

'buffered': bool, # Buffer results by default

384

'raw': bool, # Return raw results by default

385

'consume_results': bool, # Consume unread results (default: False)

386

'force_ipv6': bool, # Force IPv6 usage

387

'dsn': str, # Data source name string

388

}

389

```

390

391

### SSL/TLS Configuration

392

393

```python { .api }

394

ssl_config = {

395

'ssl_disabled': bool, # Disable SSL/TLS (default: False)

396

'ssl_cert': str, # Client certificate file path

397

'ssl_key': str, # Client private key file path

398

'ssl_ca': str, # Certificate authority file path

399

'ssl_capath': str, # Certificate authority directory path

400

'ssl_cipher': str, # SSL cipher specification

401

'ssl_verify_cert': bool, # Verify server certificate (default: False)

402

'ssl_verify_identity': bool, # Verify server identity (default: False)

403

'tls_versions': List[str], # Allowed TLS versions

404

'tls_ciphersuites': List[str], # Allowed TLS 1.3 cipher suites

405

}

406

```

407

408

### Authentication Configuration

409

410

```python { .api }

411

auth_config = {

412

'auth_plugin': str, # Authentication plugin name

413

'auth_plugin_map': Dict[str, Type], # Plugin name to class mapping

414

'password1': str, # First factor password (MFA)

415

'password2': str, # Second factor password (MFA)

416

'password3': str, # Third factor password (MFA)

417

'oci_config_file': str, # OCI config file path

418

'oci_config_profile': str, # OCI config profile name

419

'authentication_kerberos_client_mode': int, # Kerberos mode

420

'authentication_ldap_sasl_client_mode': int, # LDAP SASL mode

421

'authentication_webauthn_client_mode': int, # WebAuthn mode

422

}

423

```

424

425

### Advanced Options

426

427

```python { .api }

428

advanced_config = {

429

'converter_class': Type, # Custom converter class

430

'converter_str_fallback': bool, # String conversion fallback

431

'failover': List[Dict], # Failover server configurations

432

'option_files': List[str], # MySQL option files to read

433

'option_groups': List[str], # Option file groups to read

434

'allow_local_infile': bool, # Allow LOAD DATA LOCAL INFILE

435

'allow_local_infile_in_path': str, # Restrict LOCAL INFILE to path

436

'use_pure': bool, # Force pure Python implementation

437

'get_warnings': bool, # Automatically fetch warnings

438

'raise_on_warnings': bool, # Raise exceptions for warnings

439

'collation': str, # Connection collation

440

'autocommit': bool, # Autocommit transactions

441

'prepared': bool, # Use prepared statements by default

442

}

443

```

444

445

## Usage Examples

446

447

### Basic Connection

448

449

```python

450

import mysql.connector

451

452

# Simple connection

453

connection = mysql.connector.connect(

454

host='localhost',

455

user='myuser',

456

password='mypassword',

457

database='mydatabase'

458

)

459

460

cursor = connection.cursor()

461

cursor.execute("SELECT VERSION()")

462

version = cursor.fetchone()

463

print(f"MySQL version: {version[0]}")

464

465

cursor.close()

466

connection.close()

467

```

468

469

### Connection with SSL

470

471

```python

472

import mysql.connector

473

474

# SSL-enabled connection

475

connection = mysql.connector.connect(

476

host='mysql.example.com',

477

user='myuser',

478

password='mypassword',

479

database='mydatabase',

480

ssl_cert='/path/to/client-cert.pem',

481

ssl_key='/path/to/client-key.pem',

482

ssl_ca='/path/to/ca-cert.pem',

483

ssl_verify_cert=True,

484

ssl_verify_identity=True

485

)

486

```

487

488

### Context Manager Usage

489

490

```python

491

import mysql.connector

492

493

# Automatic connection cleanup

494

with mysql.connector.connect(

495

host='localhost',

496

user='myuser',

497

password='mypassword',

498

database='mydatabase'

499

) as connection:

500

cursor = connection.cursor()

501

cursor.execute("SELECT COUNT(*) FROM users")

502

count = cursor.fetchone()[0]

503

print(f"User count: {count}")

504

# Connection automatically closed

505

```

506

507

### Connection with Configuration Dictionary

508

509

```python

510

import mysql.connector

511

512

config = {

513

'host': 'localhost',

514

'port': 3306,

515

'user': 'myuser',

516

'password': 'mypassword',

517

'database': 'mydatabase',

518

'charset': 'utf8mb4',

519

'collation': 'utf8mb4_unicode_ci',

520

'autocommit': True,

521

'connect_timeout': 30,

522

'ssl_disabled': False,

523

'ssl_verify_cert': True

524

}

525

526

connection = mysql.connector.connect(**config)

527

```

528

529

### Checking Connection Status

530

531

```python

532

import mysql.connector

533

534

connection = mysql.connector.connect(

535

host='localhost',

536

user='myuser',

537

password='mypassword'

538

)

539

540

# Check connection status

541

if connection.is_connected():

542

print("Connected to MySQL")

543

print(f"Server version: {connection.server_version}")

544

print(f"Connection ID: {connection.connection_id}")

545

print(f"Current database: {connection.database}")

546

else:

547

print("Not connected")

548

549

# Test connection with ping

550

try:

551

connection.ping(reconnect=True)

552

print("Connection is alive")

553

except mysql.connector.Error as err:

554

print(f"Connection error: {err}")

555

556

connection.close()

557

```