dpxnrx11199 2019-08-01 21:24
浏览 148
已采纳

Golang代码中的mysql查询中的自动增量不起作用

I am working on a project using ethereum blockchain and I want to populate db with blocks data but for block_id autoincrement is not working.

code below is the create query

stmt, err := db.Prepare("CREATE TABLE IF NOT EXISTS block( block_id bigint NOT NULL AUTO_INCREMENT, block_num varchar(200), block_hash varchar(200), tx_count int, PRIMARY KEY (block_id) );")

code below is used to insert the data

func InsertBlock(db *sql.DB, block_num string, block_hash string, tx_count int) {
    stmt, err := db.Prepare("INSERT INTO block VALUES(?, ?, ?)")
    if err != nil {
        fmt.Println(err.Error())
    } else {
        fmt.Println("Preparation successfull for block insert: ")
    }

    _, err = stmt.Exec(block_num, block_hash, tx_count)
    if err != nil {
        fmt.Println(err.Error())
    } else {
        fmt.Println("Entry is block table is successfull: ")
    }
}

How can I make it auto increment?

Here is the error i am getting:

Error 1136: Column count doesn't match value count at row 1
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x38 pc=0x4e1930]

  • 写回答

1条回答 默认 最新

  • dto52236 2019-08-01 22:06
    关注

    As specified in the documentation:

    If you do not specify a list of column names for INSERT ... VALUES or INSERT ... SELECT, values for every column in the table must be provided by the VALUES list or the SELECT statement. If you do not know the order of the columns in the table, use DESCRIBE tbl_name to find out.

    That means that your query INSERT INTO block VALUES(?, ?, ?) will always fail because you are specifying only three out of for values.

    So you need to specify the list of the columns, like this:

    INSERT INTO block (block_num, block_hash, tx_count) VALUES(?, ?, ?)

    At that point MySql will not complain anymore because it knows that the missing column block_id is auto incremented so it doesn't need a value for that.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的