处决印刷的政治家

2024-09-28 22:21:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python脚本的print语句。你知道吗

print "mysql -e\"insert into test.syllabalize values (",text_index, ",", index, ",", "'",syllable,"')\""

这将输出正确的mysql语句。。。你知道吗

mysql -e"insert into test.syllabalize values ( 3 , 5 , 'abc')"

如何执行此语句?你知道吗

它只打印到标准输出。你知道吗

更新:

下面将尝试插入文本而不是变量的值。你知道吗

os.system('mysql -e"insert into test.syllabalize values (\'text_index\', \'index\', \'syllable\')"')

如何用上述语句中的变量替换值?你知道吗


Tags: texttest文本脚本标准indexmysql语句
3条回答

最简单的方法是使用system内置函数。要获得更高级的控制,请使用标准库的subprocess模块。你知道吗

另外,为了避免安全问题,请确保清理SQL查询,并注意从用户收到的输入。你知道吗

import subprocess
p = subprocess.Popen("mysql -e\"insert into test.syllabalize values (",text_index, ",", index, ",", "'",syllable,"')\"",shell=True)
p.wait()

但是您应该考虑使用一个python模块来访问mysql数据库,而不是这样做。您可以使用:

db.execute("insert into test.syllabalize values (?,?,?)", (text_index, index, syllable))

参数化查询提供了对sql注入的完全保护

事实上子流程.Popen也提供了它们

p = subprocess.Popen(["mysql", "-e", "\"insert into test.syllabalize values (",text_index, ",", index, ",", "'",syllable,"')\""])

此表单中不可能进行shell注入,但sql查询仍然易受攻击。你知道吗

既然您使用的是MySQL,为什么不使用MySQLdb呢?它更安全、更简单。你知道吗

import MySQLdb
db = MySQLdb.connect("host", "user", "pass", "db")
c = db.cursor()
c.execute("insert into test.syllabalize values ( %s , %s , %s)", (3,5,"abc"))

相关问题 更多 >