本地连接(Localhost Connection)指通过同一物理设备或虚拟环境访问数据库服务器,与远程连接形成技术对比,其核心机制包括:
主流数据库的本地连接配置参数示例:
-- MySQL启用Socket连接 [mysqld] skip-networking socket=/var/run/mysqld/mysqld.sock -- SQL Server启用Shared Memory协议 EXEC sys.sp_configure 'show advanced options', 1 RECONFIGURE EXEC sys.sp_configure 'shared memory', 1 RECONFIGURE
# 创建专用系统用户 sudo groupadd dblocal sudo useradd -G dblocal appuser # 配置MySQL sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf [mysqld] bind-address = 127.0.0.1 skip-networking socket = /var/run/mysqld/mysql-local.sock # 设置文件权限 sudo chown mysql:dblocal /var/run/mysqld/mysql-local.sock sudo chmod 660 /var/run/mysqld/mysql-local.sock # 创建数据库用户 mysql> CREATE USER 'appuser'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'StrongPass!2024'; mysql> GRANT SELECT, INSERT ON appdb.* TO 'appuser'@'localhost';
# pg_hba.conf local all appuser peer map=localusers # pg_ident.conf localusers appuser postgres
数据库类型 | 关键参数 | 推荐值 | 作用 |
---|---|---|---|
MySQL | innodb_flush_log_at_trx_commit | 2 | 平衡性能与持久化 |
PostgreSQL | shared_buffers | 25%内存 | 提升缓存命中率 |
SQL Server | max server memory | 70%物理内存 | 防止内存争用 |
MongoDB | storage.wiredTiger.engineConfig.cacheSizeGB | 50%内存 | 优化文档检索 |
连接失败
│
├─ 错误代码1045 → 检查mysql.user表权限
├─ 错误2002 (HY000) → 验证Socket路径与权限
├─ 连接超时 → 查看max_connections配置
└─ 认证方式错误 → 确认身份验证插件兼容性
引用文献
[1] Oracle MySQL 8.0 Reference Manual, Chapter 4.2.3.6 Socket Connections
[2] Microsoft SQL Server 2022 Security Guidelines, Local Connection Best Practices
[3] NIST Special Publication 800-123 Rev.1, Guide to Database Security
[4] PostgreSQL Global Development Group, Peer Authentication Documentation