简体   繁体   中英

can't see table created by pyodbc in ms access

I am accessing a MS Access Database in Python 3.6 using pyodbc library. I can read a table, no problems. The I created a simple table (Employee). I inserted records. I was able to fetch the records too by reading the table, no problems.

I also listed the tables in the MS Access DB. Employee table shows in the list.

But when I open up the MS Access Database, I do not find the table. I changed MS Access DB to show hidden and system objects. Employee table doesn't show up.

What am I doing wrong?

Thanks

Here is the code:

import pyodbc

db_file = r'''C:\TickData2018\StooqDataAnalysis.accdb'''
user = 'admin'
password = ''

odbc_conn_str = 'DRIVER={Microsoft Access Driver (*.accdb)};DBQ=%s;UID=%s;PWD=%s' %\
                (db_file, user, password)
# Or, for newer versions of the Access drivers:
odbc_conn_str = 'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=%s;UID=%s;PWD=%s' %\
                (db_file, user, password)

conn = pyodbc.connect(odbc_conn_str)

print("connection made")

c = conn.cursor()

c.execute("SELECT * FROM 5MtsBaseForAnalysisSorted")

list1 = c.fetchmany(2)

print(list1[0][0])
print(list1[0][1])
print(list1[0][2])

try:
    c.execute("""CREATE TABLE employee(
                first text,
                last text,
                pay integer
                );""")
except Exception as e:
    print(e)

conn.commit

c.execute("INSERT INTO employee VALUES ('Krishna', 'Sundar', 50000)")
c.execute("INSERT INTO employee VALUES ('Divya', 'Sundar', 70000)")
c.execute("INSERT INTO employee VALUES ('Panka', 'Sundar', 70000)")
conn.commit

c.execute("SELECT * FROM employee")
print(c.fetchall())

c.tables()
rows = c.fetchall()
for row in rows:
    print(row)


c.close()
del c
conn.close()

This is a general Python object model where you need to call the actual function and not its bounded name. Specifically, your commit lines are not correct where

conn.commit

Should be with open/close parentheses:

conn.commit()

Another way to see the difference is by reviewing the object's type:

type(conn.commit)
# <built-in method commit of pyodbc.Connection object at 0x000000000B772E40>

type(conn.commit())
# NoneType

I did reproduce your issue with exact code and adding parentheses resolved the issue.

An additional solution to manually committing is to set autocommit = True when the connection instance is created.

Eg:

conn = pyodbc.connect(odbc_conn_str, autocommit = True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM