Connect to MySQL
How to connect to MySQL databases in Python, JavaScript, and Java.
Note: This guide follows English-language naming conventions and terminology standards common in international development teams. Examples use English identifiers and comments to maximize compatibility across codebases and tooling.
Overview
MySQL remains one of the most widely deployed relational databases. Whether running locally, on AWS RDS, or in a managed cluster, connecting securely and efficiently is critical. This recipe covers MySQL connections with connection pooling, SSL, and prepared statements in Python, JavaScript, and Java.
When to Use
Use this resource when:
- Developing applications that use MySQL as the primary data store
- Migrating from MariaDB or switching from PostgreSQL to MySQL
- Writing scripts that import or export data from MySQL databases
Solution
Python
import mysql.connector
from mysql.connector import Error
# Basic connection
conn = mysql.connector.connect(
host="localhost",
database="mydb",
user="user",
password="pass",
ssl_ca="ca.pem",
ssl_verify_cert=True
)
cursor = conn.cursor(dictionary=True)
cursor.execute("SELECT * FROM users WHERE id = %s", (1,))
row = cursor.fetchone()
cursor.close()
conn.close()
JavaScript
const mysql = require('mysql2/promise');
const pool = mysql.createPool({
host: 'localhost',
database: 'mydb',
user: 'user',
password: 'pass',
ssl: { ca: require('fs').readFileSync('ca.pem') },
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
async function getUser(id) {
const [rows] = await pool.execute('SELECT * FROM users WHERE id = ?', [id]);
return rows[0];
}
Java
import java.sql.*;
public class MySQLConnect {
public Connection connect() throws SQLException {
String url = "jdbc:mysql://localhost:3306/mydb?sslMode=VERIFY_CA&serverTimezone=UTC";
return DriverManager.getConnection(url, "user", "pass");
}
public void queryUser(int id) throws SQLException {
try (Connection conn = connect();
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE id = ?")) {
stmt.setInt(1, id);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("email"));
}
}
}
}
Explanation
MySQL uses prepared statements through protocol-level placeholders (%s in Python, ? in Java, ? in mysql2). Connection pooling is essential because MySQL connections are relatively expensive to establish. The JavaScript mysql2/promise pool handles queuing when all connections are in use. The Java example uses the modern com.mysql.cj.jdbc.Driver (MySQL Connector/J) with timezone and SSL verification settings in the JDBC URL.
Variants
| Technology | Approach | Notes |
|---|---|---|
| Python | PyMySQL | Pure Python implementation, no C dependencies |
| JavaScript | mysql (non-promise) | Callback-based legacy driver |
| Java | HikariCP + MySQL Connector/J | Industry-standard pooling for Spring Boot |
Best Practices
- Use connection pooling with a limit appropriate to your database’s
max_connections - Enable SSL with certificate verification in production environments
- Set explicit connection timeouts and idle timeouts to prevent stale connections
- Use
execute()(prepared statements) instead ofquery()for user-supplied values - Store connection strings in environment variables and use IAM authentication when on AWS RDS
Common Mistakes
- Using the deprecated
mysqlpackage in Node.js instead ofmysql2 - Forgetting to set
serverTimezonein JDBC URLs, causing timezone shift bugs - Not handling connection errors, leading to unhandled promise rejections or crashes
- Using
SELECT *in production without considering column count and network overhead - Opening connections in loops instead of reusing pooled connections
Frequently Asked Questions
Should I use mysql-connector-python or PyMySQL?
mysql-connector-python is the official Oracle driver with better performance. PyMySQL is a pure-Python alternative useful when C extensions cannot be installed.
How do I handle connection timeouts in mysql2?
Set connectTimeout, acquireTimeout, and timeout in pool options. Also configure enableKeepAlive for long-running connections.
What is the difference between query() and execute() in mysql2?
query() sends the SQL as a plain string. execute() sends a prepared statement with bound parameters, which is safe against SQL injection and can improve performance for repeated queries.
Related Resources
Connect to PostgreSQL
How to connect to PostgreSQL databases in Python, JavaScript, and Java.
PatternAbstract Factory Pattern
Create families of related objects without specifying concrete classes. A creational design pattern for consistent object families.
PatternAdapter Pattern
Convert the interface of a class into another interface clients expect. A structural design pattern for interface compatibility.
PatternAmbassador Pattern
Deploy a client-side proxy that handles cross-cutting concerns for outbound service calls. A microservices pattern for smart client-side networking.
PatternBridge Pattern
Decouple an abstraction from its implementation so both can vary independently. A structural design pattern for platform independence.