Search code examples
mysqlgogo-gorm

Go Gorm raw sql create table then insert error


I got encountered some problem with Go and Gorm package. I was trying to create table and insert table using raw query. Sadly, the error said I got a syntax error in the SQL code, but when I try to execute it by using PhpMyAdmin it's just working fine.

Here is the code minimum reproduce code:

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)
    }
}

Unfortunately, it's producing the error below:

$ 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

I'm currently using Docker running MySQL container for dev. Here is the Docker compose that I'm using:

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

Solution

  • In your connection string you should add parameter multiStatements=true

    So your code would look like this:

    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)
        }
    }