Python SQL 更新语句但使用 pyodbc

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27952555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:31:23  来源:igfitidea点击:

SQL Update statement but using pyodbc

pythonsqlpyqtpyqt4pyodbc

提问by MrPython

I am using a pyodbc driver to connect to a microsoft access table using SQL. Does anyone know how I go about replacing fields within this table?? I have though about deleting the row and then putting the row back but that would change the primary key due to the autonumber in access.

我正在使用 pyodbc 驱动程序使用 SQL 连接到 microsoft access 表。有谁知道我如何替换此表中的字段?我曾想过删除该行然后将该行放回去,但这会由于访问中的自动编号而更改主键。

I have this for inserting into the Progress table:

我有这个插入进度表:

        cnxn = pyodbc.connect('Driver={Microsoft Access Driver (*.mdb, *.accdb)}; Dbq=C:\Users\...............(file location)')
        cursor = cnxn.cursor()
        cursor.execute("insert into Progress(CockpitDrill,Mirrors,MoveOff,TurnLeft) values (?,?,?,?)",cockpit,mirrors,moveOff,turnLeft,)
        cnxn.commit()

So how would I replace these fields. Let's say I wanted to change CockpitDrill from '2' to '3', (They are all strings).

那么我将如何替换这些字段。假设我想将 CockpitDrill 从“2”更改为“3”(它们都是字符串)。

Any help would be greatly appreciated.

任何帮助将不胜感激。

采纳答案by SKoczian

You can execute an UPDATE statement just as you now execute your INSERT:

您可以像现在执行 INSERT 一样执行 UPDATE 语句:

    cnxn = pyodbc.connect('Driver={Microsoft Access Driver (*.mdb, *.accdb)}; Dbq=C:\Users\...............(file location)')
    cursor = cnxn.cursor()
    cursor.execute("UPDATE progress SET CockpitDrill = ? WHERE progress_primarykey = ?", newcockpitdrillvalue, oldprimarykeyvalue)
    cnxn.commit()

Does that help? "progress_primarykey" is the assumed name I've given to the primary key field in your database table. That's supposing you just want to change one record and you know its primary key.

这有帮助吗?“progress_primarykey”是我为您的数据库表中的主键字段提供的假定名称。那是假设您只想更改一条记录并且您知道它的主键。