🔗 MySQL 连接
MySQL 连接是数据库操作的第一步。本章将详细介绍各种连接 MySQL 数据库的方法,包括命令行、图形化工具以及编程语言连接方式。
💻 命令行连接
基本连接语法
# 基本连接格式
mysql -h [主机名] -P [端口] -u [用户名] -p [数据库名]
# 本地连接示例
mysql -u root -p
# 远程连接示例
mysql -h 192.168.1.100 -P 3306 -u admin -p mydb
# 指定字符集连接
mysql -u root -p --default-character-set=utf8mb4
连接参数详解
# 常用连接参数
-h, --host=name # 服务器主机名或IP地址
-P, --port=# # 端口号(默认3306)
-u, --user=name # 用户名
-p, --password[=name] # 密码(建议不在命令行中直接输入)
-D, --database=name # 默认数据库
-e, --execute=name # 执行SQL语句后退出
--ssl-mode=mode # SSL连接模式
--protocol=name # 连接协议(TCP、SOCKET、PIPE、MEMORY)
# 示例:执行单条SQL语句
mysql -u root -p -e "SHOW DATABASES;"
# 示例:执行SQL文件
mysql -u root -p < backup.sql
# 示例:将查询结果输出到文件
mysql -u root -p -e "SELECT * FROM users;" > users.txt
MySQL 8.x 连接新特性
- 默认认证插件:使用
caching_sha2_password
- SSL 默认启用:默认要求加密连接
- 连接压缩:支持 zstd 压缩算法
# MySQL 8.x 特定连接选项
mysql -u root -p --ssl-mode=REQUIRED
mysql -u root -p --compression-algorithms=zstd
mysql -u root -p --get-server-public-key
🖥️ MySQL Workbench 连接
创建新连接
- 打开 MySQL Workbench
- 点击 "+" 号创建新连接
- 填写连接信息:
- Connection Name:连接名称(自定义)
- Hostname:主机地址
- Port:端口号(默认3306)
- Username:用户名
- Password:密码(可选择存储)
- 点击 "Test Connection" 测试连接
- 保存连接配置
高级连接选项
# SSL 配置
SSL Mode: Required/Preferred/Disabled
SSL CA File: CA证书文件路径
SSL Cert File: 客户端证书文件路径
SSL Key File: 客户端私钥文件路径
# 高级选项
Default Schema: 默认数据库
SQL_MODE: SQL模式设置
Timeout: 连接超时时间
🌐 phpMyAdmin 连接
配置文件设置
// config.inc.php 配置示例
<?php
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['port'] = '3306';
$cfg['Servers'][$i]['socket'] = '';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['user'] = '';
$cfg['Servers'][$i]['password'] = '';
// MySQL 8.x 兼容性设置
$cfg['Servers'][$i]['ssl'] = true;
$cfg['Servers'][$i]['ssl_key'] = null;
$cfg['Servers'][$i]['ssl_cert'] = null;
$cfg['Servers'][$i]['ssl_ca'] = null;
?>
phpMyAdmin 与 MySQL 8.x 兼容性
使用 phpMyAdmin 连接 MySQL 8.x 时,需要注意:
- 确保 phpMyAdmin 版本 ≥ 4.8.0
- PHP 版本 ≥ 7.2.4
- 或者修改 MySQL 用户认证方式
-- 修改用户认证方式为兼容模式
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
FLUSH PRIVILEGES;
🔧 编程语言连接示例
Python 连接
# 使用 mysql-connector-python
import mysql.connector
# MySQL 5.7 连接
config_57 = {
'host': 'localhost',
'port': 3306,
'user': 'root',
'password': 'password',
'database': 'testdb',
'charset': 'utf8mb4'
}
# MySQL 8.x 连接
config_8x = {
'host': 'localhost',
'port': 3306,
'user': 'root',
'password': 'password',
'database': 'testdb',
'charset': 'utf8mb4',
'auth_plugin': 'mysql_native_password'
}
try:
conn = mysql.connector.connect(**config_8x)
cursor = conn.cursor()
cursor.execute("SELECT VERSION()")
version = cursor.fetchone()
print(f"MySQL 版本: {version[0]}")
except mysql.connector.Error as err:
print(f"连接错误: {err}")
finally:
if conn.is_connected():
cursor.close()
conn.close()
Java 连接(JDBC)
// MySQL 5.7 连接字符串
String url57 = "jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=UTC";
// MySQL 8.x 连接字符串
String url8x = "jdbc:mysql://localhost:3306/testdb?useSSL=true&serverTimezone=UTC&allowPublicKeyRetrieval=true";
// 连接示例
import java.sql.*;
public class MySQLConnection {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb?useSSL=true&serverTimezone=UTC";
String username = "root";
String password = "password";
try {
Connection conn = DriverManager.getConnection(url, username, password);
System.out.println("连接成功!");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT VERSION()");
if (rs.next()) {
System.out.println("MySQL 版本: " + rs.getString(1));
}
conn.close();
} catch (SQLException e) {
System.out.println("连接失败: " + e.getMessage());
}
}
}
Node.js 连接
// 使用 mysql2 包
const mysql = require('mysql2');
// 创建连接
const connection = mysql.createConnection({
host: 'localhost',
port: 3306,
user: 'root',
password: 'password',
database: 'testdb',
charset: 'utf8mb4'
});
// 连接数据库
connection.connect((err) => {
if (err) {
console.error('连接失败: ' + err.stack);
return;
}
console.log('连接成功,连接ID: ' + connection.threadId);
});
// 执行查询
connection.query('SELECT VERSION() as version', (err, results) => {
if (err) throw err;
console.log('MySQL 版本:', results[0].version);
});
// 关闭连接
connection.end();
// 连接池示例
const pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: 'root',
password: 'password',
database: 'testdb',
acquireTimeout: 60000,
timeout: 60000
});
🔒 连接安全最佳实践
1. 密码安全
- 不要在命令行中直接输入密码
- 使用配置文件存储连接信息
- 定期更换数据库密码
- 使用强密码策略
2. 网络安全
# 启用 SSL 连接
mysql -u root -p --ssl-mode=REQUIRED
# 配置防火墙规则
# 只允许特定IP访问MySQL端口
iptables -A INPUT -p tcp -s 192.168.1.0/24 --dport 3306 -j ACCEPT
iptables -A INPUT -p tcp --dport 3306 -j DROP
3. 用户权限管理
-- 创建专用用户而不是使用root
CREATE USER 'app_user'@'localhost' IDENTIFIED BY 'strong_password';
-- 授予最小必要权限
GRANT SELECT, INSERT, UPDATE, DELETE ON myapp.* TO 'app_user'@'localhost';
-- 限制连接来源
CREATE USER 'remote_user'@'192.168.1.%' IDENTIFIED BY 'password';
-- 查看用户权限
SHOW GRANTS FOR 'app_user'@'localhost';
4. 连接池配置
# 连接池最佳实践
max_connections = 200 # 最大连接数
max_user_connections = 50 # 单用户最大连接数
connect_timeout = 10 # 连接超时时间
wait_timeout = 28800 # 等待超时时间
interactive_timeout = 28800 # 交互超时时间
🔍 连接故障排除
常见连接错误及解决方案
# 错误1: Access denied for user
ERROR 1045 (28000): Access denied for user 'root'@'localhost'
解决方案:
1. 检查用户名和密码
2. 重置root密码
3. 检查用户权限
# 错误2: Can't connect to MySQL server
ERROR 2003 (HY000): Can't connect to MySQL server on 'localhost'
解决方案:
1. 检查MySQL服务是否启动
2. 检查端口是否正确
3. 检查防火墙设置
# 错误3: Host is not allowed to connect
ERROR 1130 (HY000): Host '192.168.1.100' is not allowed to connect
解决方案:
1. 修改用户主机权限
2. 检查bind-address配置
# MySQL 8.x 特有错误
ERROR 2059: Authentication plugin 'caching_sha2_password' cannot be loaded
解决方案:
1. 升级客户端版本
2. 修改用户认证插件
3. 使用--get-server-public-key选项
连接测试脚本
#!/bin/bash
# MySQL 连接测试脚本
HOST="localhost"
PORT="3306"
USER="root"
PASSWORD="your_password"
echo "测试 MySQL 连接..."
# 测试端口是否开放
if nc -z $HOST $PORT; then
echo "✅ 端口 $PORT 可访问"
else
echo "❌ 端口 $PORT 不可访问"
exit 1
fi
# 测试数据库连接
if mysql -h $HOST -P $PORT -u $USER -p$PASSWORD -e "SELECT 1;" &>/dev/null; then
echo "✅ 数据库连接成功"
mysql -h $HOST -P $PORT -u $USER -p$PASSWORD -e "SELECT VERSION();"
else
echo "❌ 数据库连接失败"
exit 1
fi