[My]SQL 是否有类似预处理器的功能?

发布于 2024-08-01 22:18:30 字数 523 浏览 7 评论 0原文

我正在为我的第一个数据库驱动的应用程序编写一个小型部署 SQL 脚本。

在这个过程中,我发现我很多重复自己,例如:

GRANT USAGE ON *.* TO 'foo'@'localhost';
DROP USER 'foo'@'localhost';
CREATE USER 'foo'@'localhost' IDENTIFIED BY 'password';

如果我可以使用变量或宏来替换常见的数据,那就太棒了。 是否可以实现类似以下代码片段的内容?

#define USER 'foo'        #or "Type USER = 'foo'"
#define HOST 'localhost'  #or "Type HOST = 'localhost'"

GRANT USAGE ON *.* TO USER@HOST
DROP USER USER@HOST
CREATE USER USER@HOST IDENTIFIED BY 'password'

I'm writing a small deployment SQL script for my first database-driven app.

In the process, I find that I repeat myself a lot, for instance:

GRANT USAGE ON *.* TO 'foo'@'localhost';
DROP USER 'foo'@'localhost';
CREATE USER 'foo'@'localhost' IDENTIFIED BY 'password';

It would be fantastic if I could use a variable or a macro to replace commonly occurring data. Is it possible to implement something like the the following snippet?

#define USER 'foo'        #or "Type USER = 'foo'"
#define HOST 'localhost'  #or "Type HOST = 'localhost'"

GRANT USAGE ON *.* TO USER@HOST
DROP USER USER@HOST
CREATE USER USER@HOST IDENTIFIED BY 'password'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

枫林﹌晚霞¤ 2024-08-08 22:18:30

大多数 SQL 数据库都有某种类型的绑定变量可供您使用。

例如,在 PostgreSQL 中,您在 plsql 中使用 \set 命令:

\set user = foo
drop user :user;
create user :user identified by 'password';

但是,我不确定 MySQL 是否有类似的东西。 它确实有变量,并且由于主机和用户是一个字符串,您也许可以执行以下操作:

select @user = 'foo';
select @host = 'localhost;

drop user @user@@host;
create user @user@@host identified by 'password';

如果变量不适用于 drop 和 create user 语句,您始终可以直接修改 mysql.user 表,只是不要忘记之后执行flush特权

insert into user values(host,@user,PASSWORD('some_pass'),
       'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y');
flush privileges;

Most SQL databases have some kind of bind variables that you can use for that.

For instance, in PostgreSQL you use the \set command in plsql:

\set user = foo
drop user :user;
create user :user identified by 'password';

However, I am not sure if MySQL have something like that. It do have variables, and since the host and user is a string, you might be able to do something like this:

select @user = 'foo';
select @host = 'localhost;

drop user @user@@host;
create user @user@@host identified by 'password';

If variables doesn't work with the drop and create user statements, you can always modify the mysql.user table directly, just don't forget to execute flush privileges after.

insert into user values(host,@user,PASSWORD('some_pass'),
       'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y');
flush privileges;
最美的太阳 2024-08-08 22:18:30

你当然可以这样做:

SET @user='foo';

You can certainly do something like:

SET @user='foo';
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文