如何解决Python cx_oracle中的ORA-01704: 字符串文字过长错误?
我正在尝试用Python的cx_oracle库更新一个表中的一条记录。这个表里有一列叫“template”,它的数据类型是CLOB。
这是我的代码:
dsn = cx_Oracle.makedsn(hostname, port, sid)
orcl = cx_Oracle.connect(username + '/' + password + '@' + dsn)
curs = orcl.cursor()
sql = "update mytable set template='" + template + "' where id='6';"
curs.execute(sql)
orcl.close()
当我这样做的时候,出现了一个错误,提示字符串字面量太长。这个template变量大约有26000个字符。我该怎么解决这个问题呢?
补充:
我找到了一些信息:http://osdir.com/ml/python.db.cx-oracle/2005-04/msg00003.html
所以我尝试了这个:
curs.setinputsizes(value = cx_Oracle.CLOB)
sql = "update mytable set template='values(:value)' where id='6';"
curs.execute(sql, value = template)
结果我得到了一个“ORA-01036: 非法的变量名/数字”的错误。
补充2:
现在我的代码是这样的:
curs.setinputsizes(template = cx_Oracle.CLOB)
sql = "update mytable set template= :template where id='6';"
print sql, template
curs.execute(sql, template=template)
现在我又遇到了一个ORA-00911: 无效字符的错误。
3 个回答
-1
修改一下你的表格定义。一个 varchar2
字段最多可以存储32767个字节;所以,如果你使用的是8位编码的话,你还有一些空间可以利用,不一定非得使用LOB(大对象)来存储数据。
0
使用IronPython
import sys
sys.path.append(r"...\Oracle\odp.net.11g.64bit")
import clr
clr.AddReference("Oracle.DataAccess")
from Oracle.DataAccess.Client import OracleConnection, OracleCommand, OracleDataAdapter
connection = OracleConnection('userid=user;password=hello;datasource=database_1')
connection.Open()
command = OracleCommand()
command.Connection = connection
command.CommandText = "SQL goes here"
command.ExecuteNonQuery()
5
在SQL语句中直接插入值是个很糟糕的做法。你应该使用参数来代替:
dsn = cx_Oracle.makedsn(hostname, port, sid)
orcl = cx_Oracle.connect(username + '/' + password + '@' + dsn)
curs = orcl.cursor()
curs.setinputsizes(template = cx_Oracle.CLOB)
sql = "update mytable set template= :template where id='6'"
curs.execute(sql, template=template)
orcl.close()