Go Gorm原始SQL创建表,然后插入错误

dsekswqp  于 2023-03-16  发布在  Go
关注(0)|答案(1)|浏览(263)

我遇到了一些Go和Gorm包的问题。我试图创建表和插入表使用原始查询。可悲的是,错误说我得到了一个语法错误的SQL代码,但当我试图执行它使用PhpMyAdmin它只是工作正常。
下面是代码最小再现代码:

package main

import (
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
)

const CREATE_TABLE_SQL = "CREATE TABLE `mytable` (`a` int); INSERT INTO `mytable` (`a`) VALUES (1);"

func main() {
    dsn := "sandbox:sandbox@tcp(localhost)/sandbox?charset=utf8mb4&parseTime=True&loc=Local"
    db, err := gorm.Open(mysql.Open(dsn))
    if err != nil {
        panic(err)
    }

    err2 := db.Exec(CREATE_TABLE_SQL).Error
    if err2 != nil {
        panic(err2)
    }
}

很遗憾,它产生了以下错误:

$ go run .

2023/03/09 13:54:01 go-raw-sql-create-table-error/main.go:17 Error 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO `mytable` (`a`) VALUES (1)' at line 1       
[0.524ms] [rows:0] CREATE TABLE `mytable` (`a` int); INSERT INTO `mytable` (`a`) VALUES (1);
panic: Error 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO `mytable` (`a`) VALUES (1)' at line 1

goroutine 1 [running]:
main.main()
        go-raw-sql-create-table-error/main.go:19 +0xef
exit status 2

我目前正在使用Docker运行MySQL容器进行开发。以下是我正在使用的Docker组合:

version: '3.8'

services:
  mysql:
    image: mysql:8
    container_name: mysql
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: sandboxroot
      MYSQL_DATABASE: sandbox
      MYSQL_USER: sandbox
      MYSQL_PASSWORD: sandbox
    ports:
      - 3306:3306

  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    container_name: phpmyadmin
    restart: always
    environment:
      PMA_HOST: mysql
      PMA_PORT: 3306
      PMA_USER: sandbox
      PMA_PASSWORD: sandbox
    ports:
      - 8080:80
1tu0hz3e

1tu0hz3e1#

在连接字符串中,应添加参数multiStatements=true
因此,您的代码将如下所示:

package main

import (
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
)

const CREATE_TABLE_SQL = "CREATE TABLE `mytable` (`a` int); INSERT INTO `mytable` (`a`) VALUES (1);"

func main() {
    dsn := "sandbox:sandbox@tcp(localhost)/sandbox?charset=utf8mb4&parseTime=True&loc=Local&multiStatements=true"
    db, err := gorm.Open(mysql.Open(dsn))
    if err != nil {
        panic(err)
    }

    err2 := db.Exec(CREATE_TABLE_SQL).Error
    if err2 != nil {
        panic(err2)
    }
}

相关问题