【发布时间】:2015-09-16 00:29:07
【问题描述】:
我需要有关 python 中变量的帮助,它们将在运行时获取,如果我在选择查询中给出实际的表名它可以工作,但是当我尝试变量时它会失败。
import cx_Oracle
import csv
import sys
tablename = sys.argv[1] # pasing it as input at runtime
host = 'server.com'
port = 7111
SERVICE_NAME = 'gtpts'
login = 'USER'
passwrd = 'password'
SID = 'server.com'
dsn = cx_Oracle.makedsn(host, port, SID).replace('SID','SERVICE_NAME')
con = cx_Oracle.connect(login, passwrd, dsn)
cur = con.cursor()
cur.execute('select * from table') # direct table name works but variable doesnot
row = cur.fetchall()
报错如下:
[20020663]:20020663> python oracleconnect.py employee
Traceback (most recent call last):
File "oracleconnect.py", line 16, in <module>
cur.execute('select * from tablename')
cx_Oracle.DatabaseError: ORA-00911: invalid character
我可以通过在 perl 中使用 $variable 来做同样的事情,我们在 python 中有什么相同的吗?
【问题讨论】:
-
您正在运行
select * from table,完全按照所写,您需要使用字符串格式来替换变量。试试'select * from %s' %(table)。 -
谢谢布兰登,你分享的细节也有效。