交易失败

时间:2021-02-07 09:01:30

标签: mysql go mariadb

我正在用 Go 编写一个带有 MariaDb 连接器的应用程序,但出现以下错误。当我在命令行上手动将输出粘贴到 MySQL 中时,它运行良好。我不确定为什么它会在 Go 应用程序中失败。

BEGIN;
    INSERT INTO content (content) VALUES ('testing');
    SET @last_id_in_table1 = LAST_INSERT_ID();
    INSERT INTO article_meta
    (article_title, article_author, description)
    VALUES ('title', 'bob', '');
    SET @last_id_in_table2 = LAST_INSERT_ID();
    INSERT INTO articles
    (content_id, article_id)
    VALUES (@last_id_in_table1, @last_id_in_table2);
COMMIT;
    
2021/02/07 03:47:54 Error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INSERT INTO content (content) VALUES ('testing');
    SET @last_id_in_table1 ...' at line 2
exit status 1
MariaDB [golang]> BEGIN;
Query OK, 0 rows affected (0.000 sec)

MariaDB [golang]> INSERT INTO content (content) VALUES ('testing');
Query OK, 1 row affected (0.001 sec)

MariaDB [golang]> SET @last_id_in_table1 = LAST_INSERT_ID();
Query OK, 0 rows affected (0.000 sec)

MariaDB [golang]> INSERT INTO article_meta
    -> (article_title, article_author, description)
    -> VALUES ('title', 'bob', '');
Query OK, 1 row affected (0.056 sec)

MariaDB [golang]> SET @last_id_in_table2 = LAST_INSERT_ID();
Query OK, 0 rows affected (0.000 sec)

MariaDB [golang]> INSERT INTO articles
    -> (content_id, article_id)
    -> VALUES (@last_id_in_table1, @last_id_in_table2);
Query OK, 1 row affected (0.034 sec)

MariaDB [golang]> COMMIT;
Query OK, 0 rows affected (0.033 sec)

所有其他 MySQL 似乎在 Go 应用程序中都可以正常工作。我可以毫无问题地执行查询和插入/更新。我不知道为什么这个特定查询失败。任何帮助将不胜感激。

这是有问题的特定代码片段:

query := fmt.Sprintf(`
  BEGIN;
    INSERT INTO content (content) VALUES ('%s');
    SET @last_id_in_table1 = LAST_INSERT_ID();
    INSERT INTO article_meta
    (article_title, article_author, description)
    VALUES ('%s', '%s', '%s');
    SET @last_id_in_table2 = LAST_INSERT_ID();
    INSERT INTO articles
    (content_id, article_id)
    VALUES (@last_id_in_table1, @last_id_in_table2);
  COMMIT;
`, article.Content, article.Title, article.Auth, article.Description)

fmt.Println(query)
rows, err2 := db.Query(query)
if err2 != nil {
    log.Fatal(err2)
}

1 个答案:

答案 0 :(得分:0)

您应该使用 tx, err := db.Begin() 启动事务,然后使用 tx.Query/QueryRow/Exec 调用各个语句,然后,如果成功使用 tx.Commit() 提交该事务,或者如果不成功则使用 {{1 }} 中止。

另请注意,将 tx.Rollback()%s 结合使用会使您的代码容易受到 SQL 注入攻击。您应该改用您正在使用的 dbms 和/或驱动程序支持的“参数占位符”。就像 mysql 中的 fmt.Printf 或 postgres 中的 ?

类似下面的内容应该可以工作:

$N