Вставка значения переменной в базу данных через python - PullRequest
0 голосов
/ 25 мая 2018

Я новичок в 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 голосов
/ 25 мая 2018

Ошибка приходит отсюда:

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))

update

Для вашего второго случая - еслиy - это строка типа y = "100%", затем вы можете выполнить обновление следующим образом:

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

Это вставит 100 как int.
Обратите внимание, что кортеж размером 1 элементis (x,), not (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 и выполнить дальнейшие вычисления

Таблица Temp:

Замечания Perc

10 увеличено

...