执行php artisan migrate遇数据库连接及表已存在错误求助
阶段一:SQLSTATE[HY000] [2002] 连接被拒绝错误
错误信息
Illuminate\Database\QueryException
SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it. (SQL: select * from information_schema.tables where table_schema = econnect and table_name = migrations and table_type = 'BASE TABLE')
错误原因及解决
这个错误的核心是Laravel无法连接到MySQL服务:
- 你已经排查出是XAMPP中的MySQL未启动,启动XAMPP的MySQL(及Apache,若业务需要)即可解决基础连接问题。
- 若后续再次出现该错误,可额外检查:
- 确认
.env文件中的数据库配置与XAMPP MySQL一致:DB_HOST=127.0.0.1、DB_PORT=3306、DB_DATABASE=econnect、DB_USERNAME=root、DB_PASSWORD=(你的实际密码)。 - 若用
localhost作为DB_HOST报错,替换为127.0.0.1,避免DNS解析异常导致的连接失败。
- 确认
阶段二:SQLSTATE[42S01] 表personal_access_tokens已存在错误
错误信息
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'personal_access_tokens' already exists (SQL: create table personal_access_tokens (id bigint unsigned not null auto_increment primary key, tokenable_type varchar(255) not null, tokenable_id bigint unsigned not null, name varchar(255) not null, token varchar(64) not null, abilities text null, last_used_at timestamp null, created_at timestamp null, updated_at timestamp null) default character set utf8mb4 collate 'utf8mb4_unicode_ci')
错误原因
该表是Laravel Sanctum的默认令牌表,报错通常是以下情况之一:
- 之前已执行过该迁移,但
migrations表未记录这条迁移的执行状态。 - 手动在数据库中创建了该表,导致迁移执行时重复创建。
- 之前的迁移过程中断,表已创建但迁移未标记为完成。
解决方法
根据你的需求选择以下方案:
方案1:删除现有表后重新迁移(适合开发环境,无重要数据)
- 打开XAMPP的phpMyAdmin,找到
econnect数据库,删除personal_access_tokens表。 - 重新执行迁移命令:
php artisan migrate
方案2:手动标记迁移为已执行(需保留现有表数据)
- 找到迁移文件的时间戳:你的迁移文件名格式为
xxxx_xx_xx_000001_create_personal_access_tokens_table.php,其中xxxx_xx_xx_000001是时间戳(比如常见的2019_12_14_000001)。 - 在phpMyAdmin中执行SQL语句,将该迁移记录插入到
migrations表:
INSERT INTO migrations (migration, batch) VALUES ('xxxx_xx_xx_000001_create_personal_access_tokens_table', 1);
(替换xxxx_xx_xx_000001为你实际的迁移文件时间戳)
3. 再次执行php artisan migrate,系统会跳过已标记的迁移,继续执行剩余4个迁移文件。
方案3:回滚后重新迁移(若最近一次迁移包含该表创建)
如果该表是最近一次迁移创建的,可先回滚再重新执行:
php artisan migrate:rollback php artisan migrate
方案4:重置所有迁移(清空数据库,仅开发环境使用)
如果数据库中无需要保留的数据,可直接重置所有迁移并重新执行:
php artisan migrate:fresh
内容的提问来源于stack exchange,提问作者Rims

