如何使用Python编写查询?

时间:2019-02-13 17:16:20

标签: python sql oracle cx-oracle

我正在尝试查询将变量传递给查询。我找不到办法。

我要输入两个信息,我想同时使用这两个输入进行查询。

c.execute('SELECT DESCRIPTION,PART_REV 
             FROM ENG_PART_REVISION_REFERENCE 
            WHERE PART_NO = \'Part_No\' and Rev_no = \'Rev_no\' and STATE = \'Released\' ')

Part_noRev_no是输入。

import docx
import cx_Oracle
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx import Document
import os


try:
    doc = Document()
    Part_No = input("Please enter part_no: ")
    Rev_no = input("Please, the Rev_no: ")
    dsn_tns = cx_Oracle.makedsn('XXXXXXXXXXXXXXXXX', 'XXX', service_name='XXXXXX') #PLease I remove the correct data from this string connection.
    conn = cx_Oracle.connect(user=r'lora1app', password='lora1app', dsn=dsn_tns)
    c = conn.cursor()
    c.execute('SELECT DESCRIPTION,PART_REV FROM ENG_PART_REVISION_REFERENCE WHERE PART_NO = \'Part_No\' and Rev_no = \'Rev_no\' and STATE = \'Released\' ')


    doc.add_picture(os.path.join(os.path.dirname(__file__), 'logo.PNG'))
    doc.add_heading('Part Change Notification', 0)
    doc.add_paragraph('Part Number: '+ ' '+Part_No)
    doc.add_paragraph('Rev_no: '+' '+Rev_no)
    doc.save(os.path.join(os.path.dirname(__file__),'testing.docx'))

    for result in c:
        print (result)

    c.close()
    conn.close()



    input("Your Part_No: " +Part_No+" has been update it on the word document.")

except BaseException:
    import sys
    print(sys.exc_info()[0])
    import traceback
    print(traceback.format_exc())
finally:
    print("Document was updated it")
    input()

1 个答案:

答案 0 :(得分:1)

您需要对绑定变量使用colons

v_sql:="SELECT DESCRIPTION,PART_REV 
          FROM ENG_PART_REVISION_REFERENCE 
         WHERE PART_NO = :Part_No 
           AND REV_NO = :Rev_No 
           AND STATE = 'Released' "
c.execute(v_sql, (Part_No, Rev_No))
  • 元组中的顺序应与的出现顺序相同 变量。按顺序,Part_No是第一个,Rev_No是第二个。
  • 名称不必相同,而我之所以使用它们是因为 您的代码中的变量名。