Created
June 30, 2017 11:17
-
-
Save pbdanny/69c8c6530a4268490e45d590e5c61b54 to your computer and use it in GitHub Desktop.
Python connect MS Access
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # -*- coding: utf-8 -*- | |
| """ | |
| Created on Fri Jun 30 15:33:09 2017 | |
| @author: Thanakrit.B | |
| """ | |
| import pyodbc | |
| # Check if MS Access driver availabel | |
| [x for x in pyodbc.drivers() if x.startswith('Microsoft Access Driver')] | |
| # Connection String | |
| conn_str = ( | |
| r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};' | |
| r'DBQ=D:\\Backup\\OSS & TS - Performance\\2016\2016OSSDatabase.accdb;' | |
| ) | |
| # Initiate connection | |
| cnxn = pyodbc.connect(conn_str) | |
| # Initiate cursor | |
| crsr = cnxn.cursor() | |
| # Print all tables in database | |
| for table_info in crsr.tables(tableType='TABLE'): | |
| print(table_info.table_name) | |
| # Print all view in database | |
| for view_info in crsr.tables(tableType='VIEW'): | |
| print(view_info.table_name) | |
| # Show column name | |
| for row in crsr.columns(table = 'DataAllTypeTeam_201601'): | |
| print(row.column_name) | |
| # Use cursor for sql excution | |
| crsr.execute(""" | |
| select top 5 agent_code from DataAllTypeTeam_201601 | |
| where Status = 'N' | |
| and Source_Code like 'O%'; | |
| """) | |
| row = crsr.fetchall() | |
| print(row) | |
| # Import to pandas dataframe | |
| import pandas as pd | |
| query = "select * from DataAllTypeTeam_201601 where status = 'N' and source_code like 'O%'" | |
| df = pd.read_sql(query, cnxn) | |
| cnxn.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment