Using Python to extract data from MS Access - python

I need to extract a table from Access and print it in python. I have successfully connected the Access data base but I am not sure how to pull the table from Access and move it into a python data frame. I have inserted my code below.
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)
cur = conn.cursor()
SQLCommand = 'select *from table1'
df = cur.execute(SQLCommand)
print(df)
conn.commit()
I get no errors but all this returns is
<pyodbc.Cursor object at 0x0BCFF3A0>

The fetchall() will retrieve the result
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)
cur = conn.cursor()
SQLCommand = 'select * from table1'
cur.execute(SQLCommand)
df = cur.fetchall()
print(df)
You don't need to commit a select statement

Related

I'm using python, and I work with SELECT and UPDATE statement in a single cursor for the same table

Here is the code that I try to run
connection = mysql.connector.connect(host='host',
database="database",
user="user",
password="password")
cursor = connection.cursor()
cursor.execute("SELECT * FROM employee WHERE admin = 'true'")
dict_result = cursor.fetchone()
while dict_result is not None:
print(dict_result)
cursor.execute("UPDATE employee SET salary = 10000 WHERE uuid = '%s'" % (dict_result[0]))
dict_result = cursor.fetchone()
connection.close()
Error achieved by above:
But i got 'unread result found' error
I had a similar error where i had to commit after the fetch to make sure that all of the results was gathered as the fetch call is asynchronous.
My fix was to add:
connection.commit()
After the fetch but before the close.
Ex:
connection = mysql.connector.connect(host='host',
database="database",
user="user",
password="password")
cursor = connection.cursor()
cursor.execute("SELECT * FROM employee WHERE admin = 'true'")
dict_result = cursor.fetchone()
while dict_result is not None:
print(dict_result)
cursor.execute("UPDATE employee SET salary = 10000 WHERE uuid = '%s'" % (dict_result[0]))
dict_result = cursor.fetchone()
connection.commit()
connection.close()

How to import subset from MS Access based on condition criteria

I'm trying to use Python to create a dataframe which consists of certain rows (based on condition criteria) extracted from an MS Access table.
I can't seem to get the condition to work.
The MS Access table has column names such as Date, Course, Horse etc.
I want to, for example, get all the rows with Date = "01-Dec-2021" and Course = "Kempton".
I have managed to get the following code working with one criterion:
import pyodbc
connStr = (r"DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};" r"DBQ=C:\Users\chris\Documents\UKHR\SFF_Cum\SFFCum_py.accdb;")
conn = pyodbc.connect(connStr)
cursor = conn.cursor()
sql = "select * FROM SFF_cumQ_O where Course = ?"
cursor.execute(sql, ["Kempton"])
#print(cursor.fetchone())
print(cursor.fetchall())
cursor.close()
conn.close()
Here is my import of the rows based on Date = "01-Dec-2021" and Course = "Kempton"
import pyodbc
connStr = (r"DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};" r"DBQ=C:\Users\chris\Documents\UKHR\SFF_Cum\SFFCum_py.accdb;")
conn = pyodbc.connect(connStr)
cursor = conn.cursor()
sql = "select * FROM SFF_cumQ_O WHERE Date = '01-Dec-2021' and Course = 'Kempton'"
cursor.execute(sql)
print(cursor.fetchall())
However, when I try to import the rows based on Date = "01-Dec-2021" and Course = "Kempton" I run into this error :
"Exception has occurred: Error
('07002', '[07002] [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1. (-3010) (SQLExecDirectW)')"
I found the problem: the criteria needed to be bracketed.
Final code looks like this:
Note the table name is not necessary with the field name. So SFF_cumQ_O.Course can just be Course.
import pyodbc
connStr = (r"DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};" r"DBQ=C:\Users\chris\Documents\UKHR\SFF_Cum\SFFCum_py.accdb;")
conn = pyodbc.connect(connStr)
cursor = conn.cursor()
sql = "select * FROM SFF_cumQ_O WHERE ((SFF_cumQ_O.Course)='Kempton') AND ((SFF_cumQ_O.RaceDate)='01-Dec-21')"
#sql = "select * FROM SFF_cumQ_O WHERE Date = '01-Dec-21' and Course = ?"
#cursor.execute(sql, ["Kempton"])
cursor.execute(sql)
print(cursor.fetchall())
cursor.close()
conn.close()

Why when I tried to insert some values in the table with python the output it’s none?

I have this code
import MySQLdb
db = MySQLdb.connect("localhost", "root", "password", "db_name")
cursor = db.cursor()
cursor.execute("INSERT INTO directedEdges (`originLbl`, `targetLbl`) VALUES
('user1#enron.com', 'user2#enron.com' )")
data = cursor.fetchone()
print data
but when I execute this script the output is None and and I can't insert the values in the db. Why ?
In a first moment I thought it was a problem whit db connection, but if I execute
import MySQLdb
db = MySQLdb.connect("localhost", "root", "password", "db_name")
cursor = db.cursor()
cursor.execute("SELECT * FROM directedEdges")
data = cursor.fetchone()
print data
I see the content of the table directedEdges.
Thanks
You issued the cursor.fetchone() command immediately after inserting into the database. You don't have any queried data like that. You need to have queried some data before using fetchone(). Try this:
import MySQLdb
db = MySQLdb.connect("localhost", "root", "password", "db_name")
cursor = db.cursor()
cursor.execute("INSERT INTO directedEdges (`originLbl`, `targetLbl`) VALUES
('user1#enron.com', 'user2#enron.com' )")
# Commit your insert
db.commit()
# Query for data
cursor.execute("SELECT * FROM directedEdges")
data = cursor.fetchone()
print data

python: update mysql table

I am trying to update a mysql table with variable names. Below is the code that is not working for me:
import mysql.connector
conn= mysql.connector.connect(
host=host,
user=user,
passwd=password,
database=database
)
cur = conn.cursor()
cur.execute("update player_list set country = '%s', region = '%s',name = '%s' where id = %s "
% (country, region,name, id))
Running the "cur execute" line returns the following error:
mysql.connector.errors.InternalError: Unread result found
The ID column is an integer if it has any importance.
I don't see any code here how you've created your cursor, but looks like you need to specify buffered mode for your sql class to read.
Please, refer to official documentation and change your code to use buffer=True while creating your cursor and use it afterwards.
https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursorbuffered.html
Try
with conn.cursor() as cur:
sql = "update player_list set country = '%s', region = '%s',name = '%s' where id = %s" % (country, region,name, id)
cur.execute(sql)
conn.commit()
and add buffered = True into your conn like
connection = mysql.connector.connect([...], buffered = True)

Connecting to SQL server using PYODBC

I am able to connect to the SQL server 2008 R2 using Python in jupyter notebook, but when I select top 10 rows from a table, the results are not rendered on the screen. I do not get any error. I need to know how can I select the data from a table in SQL and the result gets displayed on the screen. Below is code that I used:
import pyodbc
con = pyodbc.connect('Trusted_Connection=yes', driver = '{ODBC Driver 13 for SQL Server}',server = 'ServerName', database = 'DBname')
cursor.execute("select top 10 accountid from Table")
rows = cursor.fetchall()
for row in rows:
print(row)
It looks like you missed creating the actual cursor:
import pyodbc
con = pyodbc.connect('Trusted_Connection=yes', driver = '{ODBC Driver 13 for SQL Server}',server = 'ServerName', database = 'DBname')
cursor = con.cursor()
cursor.execute("select top 10 accountid from Table")
rows = cursor.fetchall()
for row in rows:
print(row)
Good luck!

Categories

Resources