MySQL 连接
用命令行客户端与程序连接 MySQL 服务器。
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/mysqlThe 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.
命令行连接
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连接字符串(DSN)通常形如 user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4。每种语言的驱动大同小异:先建连接池,再取连接执行 SQL。
生产环境务必把连接信息放进配置/环境变量,不要硬编码进代码仓库;同时给应用单独建一个最小权限账号,别用 root。