如何将 cx_Oracle 中的变量与 Python3.x 绑定?

How do you bind variables in cx_Oracle with Python3.x?

我希望你能帮助我,因为我已经坚持了一段时间。第一次 post 来这里,什么不是。我会先说我是一名自动化测试员,有一点 Python 经验,但我不是专家。

我绞尽脑汁想解决这个问题,我不知道这是 cx_Oracle 的限制还是什么,但我找不到有类似问题的人。我之前几乎没有使用 cx_Oracle.

的经验

所以,这是我正在尝试做的一个小例子。我不能 post 整件事,因为我对它进行了多少改动并四处移动,这有点混乱。我将尝试做一个非常基本的版本;

    def test(self):
        #Driver is set up
        var1 = driver.find_element_by_name('blah').text
        var1 = str(var1)
        #Do some other stuff on the page
        return var1

    def foo():
        #Setup cx_Oracle and connect to DB
        sql = ('SELECT value FROM table WHERE ref = :1')
        c.execute(sql, (var1,)
        #Verify the results of the query

    class testcase(unittest.Testcase):
        def test_case(self):
            setUp(self)
            test(self)
            foo()

没有错误信息或类似的东西。它只是似乎没有看到变量的值。当我对 var1 的值进行硬编码时,它的工作原理和 returns 结果就像我通过 DBeaver 查询了数据库一样。

我试过将所有内容放在同一个函数中并得到相同的结果。

我尝试如下传递 var1,但仍然得到相同的结果:

    def test(self):
        #Driver is set up
        var1 = driver.find_element_by_name('blah').text
        #Do some other stuff on the page
        return var1

    def foo(var1):
        #Setup cx_Oracle and connect to DB
        sql = ('SELECT value FROM table WHERE ref = :1')
        c.execute(sql, (var1,))
        #Verify the results of the query

    class testcase(unittest.Testcase):
        def test_case(self):
            setUp(self)
            var1 = test(self)
            print (var1)
            foo(var1)

我一直在使用 this as a reference for binding variables,但 none 的方法对我有用。

所以,总而言之,我有 2 个函数,我想将一个变量从一个函数传递到另一个函数,但 cx_Oracle 似乎不喜欢它。我选择 cx_Oracle 因为 pyodbc 和 pypyodbc 似乎不想连接到我正在尝试与之交谈的 Oracle 10g 数据库。如果有人知道更好的工具,我什至愿意使用另一种工具?

如果您需要更多详细信息,请告诉我。

您可以使用 string.format 构建 sql

def foo(var1):
    #Setup cx_Oracle and connect to DB
    sql = 'SELECT value FROM table WHERE ref = {}'.format(var1)
    c.execute(sql)

当遇到这样的问题时,在使用它们之前插入一些打印变量的打印语句会很有帮助,这样您就知道您实际上使用了正确的变量。对您的代码进行一些更改:

def test(self):
    #Driver is set up
    var1 = str(driver.find_element_by_name('blah').text)
    #var1 is a local variable to function test

    #Do some other stuff on the page
    return var1

def foo(var1):
    #Setup cx_Oracle and connect to DB
    sql = ('SELECT value FROM table WHERE ref = :1')
    c.execute(sql, (var1,))
    #Verify the results of the query

class testcase(unittest.Testcase):
    def test_case(self):
        setUp(self)
        var1 = test(self)
        print (var1)
        foo(var1)