Cant Create tables in access with pyodbc

北慕城南 提交于 2019-11-27 13:58:19

问题


I am trying to create tables in a MS Access DB with python using pyodbc but when I run my script no tables are created and no errors are given. My code:

#!/usr/bin/env python
import pyodbc

con = pyodbc.connect(r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=Z:\Data\Instruments\testDB.accdb; Provider=MSDASQL;')
cur = con.cursor()
string = "CREATE TABLE TestTable(symbol varchar(15), leverage double, shares integer, price double)"
cur.execute(string)

What could be wrong?


回答1:


You need to commit the transaction:

import pyodbc

con = pyodbc.connect(r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=Z:\Data\Instruments\testDB.accdb; Provider=MSDASQL;')
cur = con.cursor()
string = "CREATE TABLE TestTable(symbol varchar(15), leverage double, shares integer, price double)"
cur.execute(string)
con.commit()



回答2:


Additional solutions that do not require a manual commit are:

Set autocommit = True when the connection instance is created.

Eg:

con = pyodbc.connect(your_connection_string, autocommit = True)

OR

Use a with statement that, according to Python Database connection Close, will commit anything before the connection is deleted at the end of the with block.

Eg:

with pyodbc.connect(your_connection_string) as con:

    CREATE_TABLE_CODE_WITHOUT_COMMIT

UNRELATED_CODE


来源:https://stackoverflow.com/questions/7744742/cant-create-tables-in-access-with-pyodbc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!