gre*_*ade 17
如果可能,使用Ruby DBI模块,而不是尝试引用字符串,使用参数化准备的查询,如下所示:
dbh = DBI.connect("DBI:Mysql:test:localhost", "testuser", "testpass")
sth = dbh.prepare("INSERT INTO people (id, name, height) VALUES(?, ?, ?)")
File.open("people.txt", "r") do |f|
f.each_line do |line|
name, height = line.chomp.split("\t")
sth.execute(nil, name, height)
end
end
Run Code Online (Sandbox Code Playgroud)
报价将为您妥善处理,注射将成为过去.
编辑:请注意,此示例显示nil作为execute()的第一个参数传递.它对应第一个?在查询中,DBI模块将其转换为"NULL".其他参数同样适当地引用并插入到查询中.