【问题标题】:dynamically Updating the table through python通过python动态更新表
【发布时间】:2018-05-26 15:57:14
【问题描述】:

我想更新一个表(TEMP):

value = 100 * 0.9
statement = 'update temp set tax = :1 where name = :2'
cur.execute(statement, ('value', 'emp1'))
con.commit()

还有其他方法可以动态更新表格吗?

【问题讨论】:

  • 有(无限?)许多方法可以做任何事情。你到底在问什么?
  • 表格没有以这种方式更新!我正在尝试更新
  • 如果不使用python直接将update temp set tax = 'value' where name = 'emp1'; commit;写入数据库是否更新?如果不是,那么你的问题不在 python 中。

标签: python sql cx-oracle


【解决方案1】:

去掉引号的价值。

value = 100 * 0.9
statement = 'update temp set tax = :1 where name = :2'
cur.execute(statement, (value, 'emp1'))
con.commit()

你传入的是字符串“值”而不是你的变量。

【讨论】:

    【解决方案2】:

    这是一些伪代码,因为我不知道您是特定的数据库信息。与此类似的代码应该可以工作:

    import pymysql
    
    con = pymysql.connect(host='localhost', user='random',
                      passwd='pass', db='sample')
    
    cur = con.cursor()
    
    value = 100 * 0.9
    name = 'emp1'
    cur.execute('''UPDATE temp SET tax = %d where name = %s'''
              %(value, name))
    con.commit()
    

    【讨论】:

    • 我也尝试过这种方式,但没有运气!我正在使用 Oracle 11g
    【解决方案3】:

    试试这个:

    #!/usr/bin/env python3.6
    table, tax, name = 'temp', 100 * 0.9, 'emp1'
    statement = f'update {table} set tax = :1 where name = :2'
    cur.execute(statement, (tax, name))
    con.commit()
    

    【讨论】:

    • 下面是我得到的错误 cur.execute(statement) cx_Oracle.DatabaseError: ORA-00933: SQL command not properly end
    • 愿你错过';'或者你的 sql 语句中的某个符号
    • 使用同上!也试过这种方式 cur.execute(f'update temp set tax = {tax} where name = {name}')
    • @SKB 我编辑了答案。也许您可以打印该语句并在数据库中尝试。
    • 这个不使用绑定变量,容易受到SQL注入攻击,更别提性能问题了!
    猜你喜欢
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 2012-10-29
    相关资源
    最近更新 更多