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

MySQL C++ Connector代码重建自增ID列失败,命令行可正常执行

问题解决:C++ MySQL Connector执行ALTER重建自增ID列失败

核心错误原因

你用了executeQuery()方法执行ALTER TABLE这类不返回结果集的DDL语句。executeQuery()仅适用于执行SELECT这类会返回结果的SQL,而ALTER、DROP、UPDATE这类语句需要用executeUpdate()方法,它专门处理无结果返回的SQL操作。

修改后的代码

把两处executeQuery()替换为executeUpdate(),并且不需要接收ResultSet对象(因为DDL语句不返回结果):

#include <iostream>
#include <mysql/mysql.h>
#include <mysql_connection.h>
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>

using namespace std;

int main(){
    sql::Driver        *myDriver;
    sql::Connection    *myConn; 
    sql::Statement     *myStmt;

    myDriver = get_driver_instance();
    myConn = myDriver->connect("localhost", "root", "password");
    myConn->setSchema("passwords");
    
    myStmt = myConn->createStatement();
    // 删除id列,用executeUpdate
    myStmt->executeUpdate("ALTER TABLE password_table DROP id;");

    // 重建id列,同样用executeUpdate
    myStmt->executeUpdate("ALTER TABLE password_table ADD id INT(200) NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY(id);");

    // 释放资源
    delete myStmt;
    delete myConn;

    return 0;
}

更优的ID序列修复方案

删列重建的方式有风险(比如表有外键关联时会出错),推荐用以下方法重置ID序列,无需删除列:

  • 第一步:重新给现有行按顺序赋值ID
    SET @row := 0;
    UPDATE password_table SET id = @row := @row + 1;
    
  • 第二步:重置自增起始值(MySQL会自动将AUTO_INCREMENT设为当前最大ID+1)
    ALTER TABLE password_table AUTO_INCREMENT = 1;
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 16:31:15