登录
首页 >  Golang >  Go问答

在 MySQL 中编写存储过程

来源:stackoverflow

时间:2024-03-13 10:51:27 190浏览 收藏

本篇文章给大家分享《在 MySQL 中编写存储过程》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

我正在尝试运行下面的查询,该查询存储在 .sql 文件中,然后使用 ioutils.readfile 读取并在初始化时执行

create table if not exists districts
(
    geocode integer primary key,
    name    varchar(32)
);

drop procedure if exists insert_district;

delimiter $$

create procedure insert_district(in pgeocode int, in pname varchar(32))
begin
    insert into districts(geocode, name) values (pgeocode, pname);
    select * from districts where geocode = pgeocode;
end$$
delimiter ;

我正在使用database/sql包并使用exec运行查询

Error 1064: 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 'drop procedure if exists insert_district;

DELIMITER $$

CREATE PROCEDURE insert' at line 7

据我所知,我的语法是正确的,并且我对其进行了测试,因此我无法弄清楚为什么无法从程序中正确运行相同的查询。


解决方案


Go MySQL 客户端默认不支持多条 SQL 语句。您不能只向其提供一个包含 ; 分隔语句的文本文件。

有关详细信息,请参阅 Does a Go Mysql driver exist that supports multiple statements within a single string? — 您可以使用一个选项来允许多语句。

但这仍然不支持像 DELIMITER 这样 MySQL 服务器无法识别的语句。这是 mysql client command

您有两种选择:

  • 解析 .sql 文件以查找语句终止符并一次运行一个语句。
  • 使用 .sql 文件作为输入在子进程中执行 mysql 客户端。

今天关于《在 MySQL 中编写存储过程》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>