【发布时间】:2021-05-11 03:28:57
【问题描述】:
我正在用 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)
在 Go 应用程序中,所有其他 MySQL 似乎都可以正常工作。我可以毫无问题地执行查询和插入/更新。我不知道为什么这个特定的查询会失败。任何帮助将不胜感激。
这是有问题的具体代码sn-p:
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)
}
【问题讨论】:
-
您应该使用
tx, err := db.Begin()启动事务,然后使用tx.Query/QueryRow/Exec调用individual 语句,然后,如果成功使用tx.Commit()提交该事务或, 如果不成功tx.Rollback()中止。 -
还要注意,将
%s与fmt.Printf一起使用会使您的代码容易受到SQL 注入的攻击。您应该改用您正在使用的 dbms 和/或驱动程序支持的“参数占位符”。就像 mysql 中的?或 postgres 中的$N。