MySQL 连接

用命令行客户端与程序连接 MySQL 服务器。

Beginner
Key Points命令行用 `mysql -h -u -p`;程序用各语言驱动走 TCP 3306 端口。

命令行连接

Shell
mysql -h 127.0.0.1 -P 3306 -u root -p
# 进入后能看到 mysql> 提示符
Output
Enter password: ********
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
mysql>

连接参数速查

参数含义
-h主机,默认 localhost
-P端口,默认 3306
-u用户名
-p提示输入密码
-e直接执行 SQL 后退出

程序里连接

Shell
# Python
pip install pymysql
# Node.js
npm install mysql2
# Go
go get -u github.com/go-sql-driver/mysql

The DSN usually looks like user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4. Every driver is similar: open a pool, grab a connection, run SQL.

In production keep connection info in config/env vars, never hardcode it, and give the app its own least-privilege account instead of root.

Friends & Partners