如何编写“创建用户?";用MySQL准备好的语句 [英] How to write "create user ?" with MySQL prepared statement

查看:88
本文介绍了如何编写“创建用户?";用MySQL准备好的语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试过:

SET @user = 'foo@localhost';
SET @pass = 'bar';
SET @sql = 'CREATE USER ? IDENTIFIED BY ?';
PREPARE stmt FROM $sql;

我收到错误消息

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 '? IDENTIFIED BY ?'

我还尝试了多种方法来定义变量,但仍然没有运气.

I also tried multiple variants how to define variables, but still without any luck.

SET @user = "'foo'@'localhost'";
SET @sql = 'CREATE USER ? IDENTIFIED BY ?';

甚至

SET @user = 'foo';
SET @host = 'localhost';
SET @sql = 'CREATE USER ?@? IDENTIFIED BY ?';

两年多以前已经问过类似的问题,但是仍然没有有用的答案:( 使用MySQLi准备语句创建用户

Quite similar question was already asked more than 2 years ago, but there still is no useful answer :( Create User with MySQLi Prepared Statement

推荐答案

这是我设法创建用户的唯一方法,不幸的是,它不对用户变量使用占位符:

This is the only way how I managed to create a user, unfortunately it doesn't use placeholders for the user variables:

SET @user := 'foo';
SET @host := 'localhost';
SET @pass := 'bar';
SET @sql := CONCAT("CREATE USER ", QUOTE(@user), "@", QUOTE(@host), " IDENTIFIED BY ", QUOTE(@pass));
PREPARE stmt FROM @sql;
EXECUTE stmt;

P.S.从MySQL 5.1.12开始应支持{CREATE | RENAME | DROP} USER语句

P.S. {CREATE | RENAME | DROP} USER statements should be supported starting from MySQL 5.1.12

这篇关于如何编写“创建用户?";用MySQL准备好的语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆