通过python

时间:2018-05-25 13:03:12

标签: python database insert

我是Python的新手,所以在这个问题上需要一些帮助: 这里我试图在数据库中插入值,当我尝试给出硬编码值然后插入时,

注意:common_test2只有2个单词

但是当我写下面的时候:

import cx_Oracle
con = cx_Oracle.connect('sys/sys@127.0.0.1:1599/xe')
print(con.version) //just to check the connection
print("this connection is established") //connection is tested
cur=con.cursor()

f3= open("common_test2", 'r+')
string= f3.read()
common_words=string.split()
x=common_words[0]
y=common_words[1]
cur.execute("INSERT INTO test(name,id) VALUES (%s,%d)", ('hello',30))
con.commit()

错误是 错误是cx_Oracle.DatabaseError:ORA-01036:非法变量名称/编号

还尝试了cur.execute("INSERT INTO test(name,id) VALUES (x, y)") 但没有运气 错误是 cx_Oracle.DatabaseError:ORA-00984:此处不允许列

任何帮助?

#I am using this for updating the table
y=100%
x=text
cur.execute("update temp set perc=(:1)", (y))
#Please note: I only want 100 to be updated in the table not the % (only 100 as numeric)
cur.execute("update temp set remarks=(:1)",(x))

1 个答案:

答案 0 :(得分:0)

错误来自:

cur.execute("INSERT INTO test(name,id) VALUES (%s,%d)", ('hello',30))

尝试使用:n指针:

cur.execute("INSERT INTO test(name, id) VALUES (:1, :2)", ('hello', 30))

更新

对于您的第二种情况 - 如果yy = "100%"之类的字符串,那么您可以通过这种方式进行更新:

cur.execute("update temp set perc = :1", (y[:-1],))

这会将100作为int插入 请注意,单项大小的元组为(x,) (x)

代码我正在使用

import cx_Oracle

con = cx_Oracle.connect('system/system@127.0.0.1:1521/xe')

# print(con.version)
# 
# print("this connection is established")

cur = con.cursor()

f3 = open("common.txt", 'r+') #this text file have only 2 words lets say (10% increased)

string = f3.read() #will read common.txt

common_words = string.split() 

x = common_words[0]     #here x have 10%

y = common_words[1]     #here y have increased

# Now I want 10 should be updated in the temp table **Not 10%** 

cur.execute("update temp set perc=(:1)", (y[:-1],))
cur.execute("update temp set remarks=(:1)", (y))

con.commit

注意:我必须检索10并进行进一步的计算

表温度:

perc备注

10增加