2011-05-01 114 views
0

我在python脚本中有打印语句。执行打印语句

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\')"') 

如何用上述语句中的变量替换值?

回答

3
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注入完整的保护

其实subprocess.Popen提供了他们太多

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

无壳注入可能以这种形式,但SQL查询仍然很脆弱。

0

最简单的方法是使用system内置函数。要进行更高级的控制,请使用标准库的subprocess模块。

P.S.为了避免安全问题,请确保清理SQL查询并防止从用户那里收到输入。

+1

,所有命令都应该通过子模块来完成 – 2011-05-01 13:56:48

+0

使用os.system就是我一直在寻找。但它将在数据库中插入变量名称而不是变量值。我更新了我的问题。 – shantanuo 2011-05-01 14:54:03

2

由于您使用的是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")) 
0

我不知道这是否是你想要的。但这是一个尝试。使用os.system不使用

test_index = 3 
index = 5 
syllable = 'abc' 

os.system('mysql -e"insert into test.syllabalize values ({0}, {1}, {2})"' % (test_index, index, syllable)) 
+0

#Python 2.4.3#AttributeError:'str'对象没有属性'格式' – shantanuo 2011-05-02 03:06:55

+0

是的,Python 2.4.3不包含格式。它是在2.6中添加的。对于2.4.3,您需要: os.system('mysql -e“insert into test.syllabalize values(%s,%s,%s)''%(test_index,index,syllable)) – 2011-05-03 23:24:04