使用mysql2 ruby​​ gem创建准备好的语句

问题描述

我是红宝石的新手,为了帮助我学习,我创建了一个小的命令行脚本,该脚本在MysqL / MariaDB中创建数据库用户。我正在尝试使用mysql2 package,但是遇到了问题。这是我遇到问题的代码,我剔除了所有与无关的东西:

#!/usr/bin/env ruby

require 'MysqL2'

root_password = 'root-pass-here'
user_name = 'jonny-5'
user_password = '5hortCi4cuit'

client = MysqL2::Client.new(:host => "localhost",:username => "root",:password => root_password)
statement = client.prepare("CREATE USER '?'@'localhost' IDENTIFIED BY '?';")
result = statement.execute(user_name,user_password)

p result

宝石文件

source 'https://rubygems.org'

gem 'MysqL2','0.5.3'

我已经尝试了所有这些方法

client.prepare("CREATE USER '?'@'localhost' IDENTIFIED BY '?';")
client.prepare("CREATE USER `?`@`localhost` IDENTIFIED BY `?`;")
client.prepare("CREATE USER (?)@'localhost' IDENTIFIED BY (?);")
client.prepare("CREATE USER ?@'localhost' IDENTIFIED BY ?;")

并出现以下错误

Bind parameter count (0) doesn't match number of arguments (2) (MysqL2::Error)
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 '`?`' at line 1 (MysqL2::Error)
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 '(?)@'localhost' IDENTIFIED BY (?)' at line 1 (MysqL2::Error)
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 '?@'localhost' IDENTIFIED BY ?' at line 1 (MysqL2::Error)

因此,如果我使用我认为正确的语法,它将找不到我的问号;如果使用其他任何一个,就好像它找到了问号,但是在执行查询之前不会替换它们。

我使用的是MariaDB而不是MysqL,但MysqL2 gem表示它确实支持MariaDB。我正在运行10.4.13,该文件未在github页面上列出,它们最高只能达到10.3,但是我已经通过命令行测试了CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';语法,并且该语法有效,所以我认为这不是问题。

谁能告诉我我要去哪里错了?

解决方法

SQL占位符替换整个参数,并且它们正确处理字符串和数字。这就是为什么它们被用来防止SQL注入。您是否尝试过将占位符放在引号中?

statement = client.prepare('CREATE USER ? IDENTIFIED BY ?;')

new_users.each do |user|
  statement.execute("#{user}@localhost",'pa55word')
end
# not tested,I don't have SQL installed