I am unable to write this df into the access table.
What am I not doing right?
conn_str = (
r'DRIVER={Microsoft Access Driver (*.mdb)};'
r'DBQ=C:\Users\harsh\Desktop\Database1.mdb;'
)
cnxn = pyodbc.connect(conn_str)
SQL = 'SELECT * FROM Index_data;'
dfins = pd.read_sql(SQL, cnxn)
for index, row in dfins.iterrows():
with cnxn.cursor() as crsr:
crsr.execute('select * from df')
conn.commit()
You probably have not installed ODBC driver for MS Access, or its name
"Microsoft Access Driver (*.mdb)"
don't agree with the string used in your program — for newer versions of Microsoft Access it is
"Microsoft Access Driver (*.mdb, *.accdb)".
So verify its name, or install it:
Open Control Panel, select Administrative Tools, then ODBC Data Sources.
New window will open up. Select “User DSN” tab.
Then verify the driver name, or install an appropriate Microsoft Access Driver — see for example Steps to create a New ODBC Connection on Windows 10.
Related
The database teacher in college gave me a task to get all the fields from the "Кураторы" table. Yep, he likes MS Acces...
Seems like something's wrong with my drivers. I'm using Windows 10 N tho. Already have checked ODBC data sources and founded some curious things. There are Microsoft Access Driver, but on ODBC Data Source Administrator (x32) only! x64 one has only one SQL Server driver
Using pyodbc-4.0.30-cp38-cp38-win_amd64 version of pyodbc and x64 Python 3.8
Getting this error:
Traceback (most recent call last):
File "D:/Documents/College/4th grade/DB/13.09.py", line 3, in <module>
conn = pyodbc.connect(r'DRIVER={Microsoft Access Driver(*.mdb, *.accdb)};DBQ=C:\Users\reddk\Desktop\db.accdb')
pyodbc.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
Here's the code:
import pyobc
conn = pyodbc.connect(r'DRIVER={Microsoft Access Driver(*.mdb, *.accdb)};DBQ=C:\Users\reddk\Desktop\db.accdb') # connecting to DB
cursor = conn.cursor()
cursor.execute('SELECT * FROM Кураторы') # request
result = cursor.fetchall() # converting the result of a query to the list of rows and assign it to the result
for row in result:
print(row) # printing each row of the list
Appreciate any help sm!
I am new in python and I need this query to check my database if it is working. There are lots of queries but it is only one of them.
import pyodbc
db_file = 'C:\\Users\\****\\Desktop\\bbbb.mdb' #define the location of your Access file
odbc_conn_str = 'DRIVER={Microsoft Access Driver (*.mdb)};DBQ=%s' %(db_file) # define the odbc connection parameter
conn = pyodbc.connect(odbc_conn_str)
cursor = conn.cursor() # create a cursor
sql_update_statement = "UPDATE NUMARATAJ SET KAPINUMERIK = IIf (ISNUMERIC (LEFT (REPLACE(KAPINO,'-','/'),4)=-1),LEFT(KAPINO,4))" # edit the SQL statement that you want to execute
cursor.execute(sql_update_statement) # execute the SQL statement
cursor.commit()
cursor.close()
conn.close()
When I try to run this code it says;
File "C:\Users\****\Desktop\aa2a.py", line 9, in <module>
cursor.execute(sql_update_statement) # execute the SQL statement
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Microsoft Access Sürücüsü] Undefined 'REPLACE' function in the expression. (-3102) (SQLExecDirectW)")
How can I fix it, or get it work, can you help me?
It could be:
sql_update_statement = "UPDATE NUMARATAJ SET KAPINUMERIK = LEFT(KAPINO,4) WHERE ISNUMERIC(LEFT(REPLACE(KAPINO,'-','/'),4)"
However, Replace is a VBA function, not Access SQL, so that is probably why you receive the error.
Try simply:
sql_update_statement = "UPDATE NUMARATAJ SET KAPINUMERIK = LEFT(KAPINO,4) WHERE ISNUMERIC(LEFT(KAPINO),4)"
There are several "VBA functions" that were not directly supported by the older "Jet" ODBC driver (Microsoft Access Driver (*.mdb)) but are directly supported by the newer "ACE" ODBC driver (Microsoft Access Driver (*.mdb, *.accdb)). Replace is one of those functions.
So if you really need to use the Replace function you can download and install the 32-bit version of the Access Database Engine Redistributable and use the newer ODBC driver.
Using Python: when connecting to SQL Server using pyodbc, everything works fine, but when I switch to sqlalchemy, the connection fails, giving me the error message:
('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
My code:
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=servername;DATABASE=dbname;UID=username;PWD=password')
engine = sqlalchemy.create_engine("mssql+pyodbc://username:password#servername/dbname")
I can't find the error in my code, and don't understand why the first options works, but the second doesn't.
Help is highly appreciated!
Ran into this problem as well, appending a driver query string to the end of my connection path worked:
"mssql+pyodbc://" + uname + ":" + pword + "#" + server + "/" + dbname + "?driver=SQL+Server"
Update (July 2021) – As above, just modernized (Python 3.6+):
f"mssql+pyodbc://{uname}:{pword}#{server}:{port}/{dbname}?driver=ODBC+Driver+17+for+SQL+Server"
Note that driver= must be all lowercase.
It works using pymssql, instead of pyodbc.
Install pymssql using pip, then change your code to:
engine = sqlalchemy.create_engine("mssql+pymssql://username:password#servername/dbname")
Very late, but experienced the same such problem myself recently. Turned out it was a problem with the latest SQLAlchemy version. Had to rollback my version from 1.4.17 to 1.4.12 (unsure of in-between versions, just went with a version I knew worked).
pip install sqlalchemy==1.4.12
I had original poster's problem with a trusted connection to the Microsoft SQL Server database (pandas 1.5.3, SQLAlchemy 2.0.4). Using answers from this question, this did the trick for me:
import sqlalchemy
import pandas as pd
server = "servername"
database = "dbname"
driver = "ODBC+Driver+17+for+SQL+Server"
url = f"mssql+pyodbc://{server}/{database}?trusted_connection=yes&driver={driver}"
engine = sqlalchemy.create_engine(url)
query = """
SELECT [column1]
,[column2] as some_other_name
FROM [server].[dbo].[table]"""
with engine.begin() as conn:
sqla_query = sqlalchemy.text(query)
df = pd.read_sql(sqla_query, conn)
It should be noted that pandas is not yet fully compatible with SQLAlchemy 2.0: https://pandas.pydata.org/docs/whatsnew/v1.5.3.html
I am new to Python and have been assigned the task to copy all the MS Access database files(we have five) into CSV format using Python. I have searched through lots of posts on Stack Overflow and sketched together this amateur snippet. I need to see the files I have in my MS Access database. Can someone please provide assistance.
Pyodbc Error - Python to MS Access
open access file in python
import pyodbc
conn_string = ("DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=T:\\DataDump\\7.18.2016 PCR etrakit.accdb")
conn = pyodbc.connect(conn_string)
cursor = conn.cursor()
cursor.close()
conn.close()
print 'All done for now'
[UPDATED]Try running this
conn_string = ("DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\\T:\\DataDump\\7.18.2016 PCR etrakit.accdb")
use double backslash instead.
Per this post:
Try doing it as a single line
conn_string = r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};C:\\T:\\DataDump\\7.18.2016 PCR etrakit.accdb;'
However, I am a bit confused by your file path. On the root of your C:\ drive, you have a directory named T:?
It may also be worth noting that file paths with spaces in the name are not always handled as expected. An alternate approach would be to try and escape the spaces in your file path:
conn_string = r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};C:\\T:\\DataDump\\7.18.2016\ PCR\ etrakit.accdb;'
I'm trying to store the current time in my access database with the following script:
import pyodbc
import time
connStr = """
DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};
DBQ=C:/Users/QPCS Registration/Documents/DB Tests/PYODBC.accdb;
"""
cnxn = pyodbc.connect(connStr)
cursor = cnxn.cursor()
def TimeStamp():
RFID = str(input("Please tap your pass on the reader:\n"))
Current_Time = str(time.strftime("%H:%M"))
cursor.execute('INSERT INTO Time_Of_Entry(RFID_Number,Time_Tapped) VALUES('+RFID+','+Current_Time+');')
cnxn.commit()
def Close_DB_Cnxn():
cnxn.close()
TimeStamp()
Close_DB_Cnxn()
When I run it I get the following error:
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Microsoft Access Driver] Syntax error (missing operator) in query expression '19:44'. (-3100) (SQLExecDirectW)")
The problem is definitely with 'Current_Time', because when I try to store the variable 'RFID' with the script shown below, it inserts into the database just fine.
cursor.execute('INSERT INTO Time_Of_Entry(RFID_Number) VALUES('+RFID+');')
I have tried changing the data type of the field 'Time_Tapped' in the table 'Time_Of_Entry' from Short Text, to Date/Time;Short Time but that has had no effect.
My machine is running on windows 7 home premium 64-bit. I have Microsoft office 2010; 32-bit I'm running python 3.3; 32-bit
Parameterized queries are useful for both INSERT queries and SELECT queries when Date/Time values are involved. Instead of messing with date/time formats and delimiters you just pass the Date/Time value as a parameter and let the data access layer (ODBC in this case) sort it out.
The following example works for me:
from datetime import datetime, time
import pypyodbc
rfid = "GORD123" ## for testing
now = datetime.now()
currentTime = datetime(1899, 12, 30, now.hour, now.minute)
connStr = """
Driver={Microsoft Access Driver (*.mdb, *.accdb)};
Dbq=C:/Users/Public/Database1.accdb;
"""
cnxn = pypyodbc.connect(connStr)
cursor = cnxn.cursor()
sql = """
INSERT INTO Time_Of_Entry (RFID_Number, Time_Tapped) VALUES (?, ?)
"""
parameters = (rfid, currentTime)
cursor.execute(sql, parameters)
cursor.close()
cnxn.commit()
cnxn.close()
Notes:
I used pypyodbc instead of pyodbc because I was using Python 3.4.3 and the latest pyodbc installer for Windows choked when it couldn't find Python 3.3. To get pypyodbc all I had to do was run pip install pypyodbc.
All date/time values in Access have both a date and time component. In order for a date/time value to appear by default as time-only in Access we need to assign it the "magic" date 1899-12-30. (That's the date corresponding to CDate(0) in Access.)