JUANLUISSG
JUANLUISSG

Reputation: 63

How can I write a query using Python?

I am trying to query passing a variable to the query. I can not find a way to do it.

I am asking for two input and I am trying to use both inputs to query.

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_no and Rev_no are inputs.

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

Upvotes: 1

Views: 74

Answers (1)

Barbaros Özhan
Barbaros Özhan

Reputation: 65228

You need to use colons for the bind variables

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))
  • The order in the tuple should be as the appearance order of variables.that's Part_No is the first, and the Rev_No is the second in the order.
  • The names needn't to be identical, whereas I used them as so because of your variable names in your code.

Upvotes: 1

Related Questions