You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Homestead中运行Laravel迁移遇SQLSTATE[HY000][2002]错误的解决求助

Homestead中Laravel迁移报错(SQLSTATE[HY000] [2002])的解决及端口验证方法

问题场景

已完成以下配置:

  • Homestead.yaml中添加数据库与端口映射:
databases:
   ...
    - ProjectName

ports:
    - send: 33060 # MySQL/MariaDB
    to: 3306
  • 项目.env文件配置数据库连接参数:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=33060
DB_DATABASE=ProjectName
DB_USERNAME=root
DB_PASSWORD=root
  • 额外操作:在Homestead的phpMyAdmin创建了ProjectName数据库、手动复制其他项目的migrations表、执行php artisan config:cache清理缓存

执行php artisan migrate时抛出错误:

Illuminate\Database\QueryException 

  SQLSTATE[HY000] [2002]  (SQL: select * from information_schema.tables where table_schema = ProjectName and table_name = migrations and table_type = 'BASE TABLE')

  at vendor/laravel/framework/src/Illuminate/Database/Connection.php:712
    708▕         // If an exception occurs when attempting to run a query, we'll format the error
    709▕         // message to include the bindings with SQL, which will make this exception a
    710▕         // lot more helpful to the developer instead of just the database's errors.
    711▕         catch (Exception $e) {
  ➜ 712▕             throw new QueryException(
    713▕                 $query, $this->prepareBindings($bindings), $e
    714▕             );
    715▕         }
    716▕     }

      +33 vendor frames 
  34  artisan:37
      Illuminate\Foundation\Console\Kernel::handle()

解决方案

1. 修正虚拟机内的数据库连接配置

在vagrant bash中执行artisan命令时,你处于Homestead虚拟机内部,此时不需要走宿主机的端口映射。修改项目.env文件:

DB_HOST=localhost # 或虚拟机内部的127.0.0.1
DB_PORT=3306      # 虚拟机内部MySQL默认端口,不是宿主机的33060

端口映射是给宿主机访问虚拟机MySQL用的,虚拟机内部直接连本地3306端口即可。

2. 删除手动复制的migrations表

手动复制其他项目的migrations表会导致Laravel迁移状态紊乱,执行以下SQL删除该表:

DROP TABLE IF EXISTS ProjectName.migrations;

让php artisan migrate命令自行创建并管理migrations表。

3. 重新清理配置缓存

执行config:cache后再执行config:clear确保配置完全刷新:

php artisan config:clear

如果仍有问题,可重启虚拟机内的服务:

sudo service nginx restart
sudo service php8.2-fpm restart # 替换为你Homestead使用的PHP版本

4. 验证数据库用户权限

在vagrant bash中登录MySQL,确认root用户能正常访问ProjectName数据库:

mysql -u root -proot

进入MySQL后执行:

USE ProjectName;
SHOW TABLES;

如果报错权限不足,执行授权命令:

GRANT ALL PRIVILEGES ON ProjectName.* TO 'root'@'localhost';
FLUSH PRIVILEGES;

端口映射有效性验证方法

方法1:宿主机MySQL客户端连接测试

打开宿主机的MySQL客户端(如Navicat、MySQL Workbench),使用以下参数连接:

  • 主机:127.0.0.1
  • 端口:33060
  • 用户名:root
  • 密码:root
  • 数据库:ProjectName
    能成功连接并查看数据,说明端口映射有效。

方法2:宿主机命令行端口连通性测试

在宿主机终端执行:

# 使用telnet
telnet 127.0.0.1 33060

# 或使用nc(需先安装)
nc -zv 127.0.0.1 33060

显示连接成功则端口映射正常。

方法3:查看Homestead端口映射列表

在宿主机执行以下命令,检查是否存在33060 => 3306的映射条目:

vagrant port

若存在该条目,说明端口配置已生效。

内容的提问来源于stack exchange,提问作者mstdmstd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 14:46:02