Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cant Create tables in access with pyodbc

Tags:

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?

like image 888
wDroter Avatar asked Oct 12 '11 18:10

wDroter


People also ask

Can Python use Access database?

To access databases in Python, you'll need to use a database adapter. Python offers database adapters through its modules that allow access to major databases such as MySQL, PostgreSQL, SQL Server, and SQLite. Furthermore, all of these modules rely on Python's database API (DB-API) for managing databases.

Can you create a table in access using SQL?

To build a new table in Access by using Access SQL, you must name the table, name the fields, and define the type of data that the fields will contain. Use the CREATE TABLE statement to define the table in SQL.


2 Answers

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()
like image 145
garnertb Avatar answered Sep 18 '22 09:09

garnertb


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
like image 37
johnDanger Avatar answered Sep 17 '22 09:09

johnDanger