I have a problem with updating an existing Access table. I have an Access database that's supposed to sort some .log files with two columns: filename and filedate. I have the filename and filedate in an Excel file that I have made from sorting through 100+ .log files, so there are 100+ files that should be linked to Access
I get an error every time and have tried many different things. The problem is that I don't know how to write the syntax. Can someone help me with that please? I want A -> filename and B -> filedate so that every pair gets its own ID
import pypyodbc
UDC = r'C:\Users\Kaiser\Documents\Access\UDC.accdb'
# DSN Connection
#constr = " DSN=MS Access Database; DBQ={0};".format(UDC)
# DRIVER connection
constr = "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};UID=admin;UserCommitSync=Yes;Threads=3;SafeTransactions=0;PageTimeout=5;MaxScanRows=8;MaxBufferSize=2048;FIL={MS Access};DriverId=25;DefaultDir=C:/USERS/DOCUMENTS/ACCESS;DBQ=C:/USERS/DOCUMENTS/ACCESS/UDC.accdb"
# Connect to database UDC and open cursor
db = pypyodbc.connect(constr)
cursor = db.cursor()
sql = "UPDATE * INTO [tblLogfile]" + \
"FROM [Excel 8.0;HDR=YES;Database=C:/Users/Documents/Access/Excel.xls].[Tab$];"
cursor.execute(sql)
db.commit()
cursor.close()
db.close()
error
pypyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Microsoft Access Driver] Syntax error in UPDATE statement.')
You need SQL something like:
sql = "INSERT INTO [tblLogfile] (<list of field names>) SELECT <list of matching field names> FROM [Excel 8.0;HDR=YES;Database=C:/Users/Documents/Access/Excel.xls].[Tab$];"
Related
I'm using 32-bit Python along with 32-bit Microsoft Access.
I connect to the database and create a cursor.
conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=P:\path\database.accdb;')
c = conn.cursor()
I then read in a table for future use:
c.execute('select * from tbl')
tbl = c.fetchall()
But when I try to make a copy of the table using:
query = 'CREATE TABLE tbl2 LIKE tbl'
c.execute(query)
I get a programming error:
ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Microsoft Access Driver] Syntax error in CREATE TABLE statement. (-3551) (SQLExecDirectW)')
I'm new to PYODBC but this is a pretty basic SQL line. Any tips on what might be wrong?
Due to a lack of documentation, the best way I found to figure this out is to use Microsoft Access to create a template for the query...example below worked.
query = 'SELECT tbl.* INTO tbl2 FROM tbl'
c.execute(query)
I don't understand? Why I receve error: 'HY000', 'The driver did not supply an error!When I insert date time? But when I insert Null all is work. Please help me with it.
My code:
now=now.strftime('%Y-%m-%d %H:%M:%S')
connect = pyodbc.connect("DRIVER={SQL Server};Server=Study;Database=test;Trusted_Connection=yes;", autocommit=False)
cursor=connect.cursor()
cursor.execute("""
use base_for_time insert table_for_time_and_count values (Null,'"""+now+"""',Null,Null,Null)""")
connect.commit()
connect.close()
This might useful.
I think the issue is in your query and in your connection.
update connection:
connect = pyodbc.connect("DRIVER={SQL Server};SERVER=*****;UID=****;PWD=****;TRUSTED_CONNECTION=yes;", autocommit=False)
you're using executing multiple SQL statements in your single execution.
execute your statements one by one or use semicolon(;) instead between two queries.
cursor.execute("use db_name; insert into table_name values (val1,val2,..,valn);")
I cannot get Python Turbodbc to connect to a Sql Server table, simple as that seems, to read or write user tables. However I have established ODBC connection, and can print a list of objects from it.
1 List objects from server to test connection. Seems to work:
from turbodbc import connect, make_options
options = make_options(prefer_unicode=True)
connection = connect(dsn='FPA', turbodbc_options=options)
cursor = connection.cursor()
cursor.execute('''SELECT * FROM sys.objects WHERE schema_id = SCHEMA_ID('dbo');''')
2 Simple Select: Does not work
cursor.execute('''SELECT * from [dbo].[Kits_Rec];''')
From #1 I get
From # 2 message: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name 'dbo.Kits_Rec'.
enter image description here
A SQL Server contains multiple databases, your dsn "FPA" probably doesn't specify the database name, so you are connecting to the master database instead of the database containing your Kits_Rec table.
Fix that dsn entry to specify the correct database, or use this syntax instead :
connection = connect(driver="MSSQL Driver",
server="hostname",
port="1433",
database="myDataBase",
uid="myUsername",
pwd="myPassword")
From my Python application, I am trying to open an ADODB connection of Excel. The code is as below:
# Create Connection object and connect to database.
ado_conn = win32com.client.gencache.EnsureDispatch('ADODB.Connection')
ado_conn.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\\Test1.xlsx; Extended Properties ='Excel 12.0 Xml;HDR=YES'";
ado_conn.Open()
# Now create a RecordSet object and open a table
oRS = win32com.client.gencache.EnsureDispatch('ADODB.Recordset')
oRS.ActiveConnection = ado_conn # Set the recordset to connect thru oConn
oRS.Open("SELECT * FROM [Orders]")
When I debug the application, it throws the error:
com_error(-2147352567, 'Exception occurred.', (0, 'Microsoft Access Database Engine', "The Microsoft Access database engine could not find the object 'Orders'. Make sure the object exists and that you spell its name and the path name correctly. If 'Orders' is not a local object, check your network connection or contact the server administrator.", None, 5003011, -2147217865), None)
In the Excel sheet the connection string looks like this:
Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=Orders;Extended Properties=""
The Command Text is:
Select * from [Orders]
Even if the connection is there, it is throwing this error.
How to execute the above Excel query from Python application?
Edit: Excel connection screenshot added below
To use the Jet/ACE SQL Engine to query Excel workbooks, you must use the $ address referencing which can be extended for specific cell ranges:
SELECT * from [Orders$]
SELECT * from [Orders$B4:Y100]
With that said, consider querying Excel workbooks directly from Python with either OLEDB provider or ODBC driver version and avoid the COM interfacing of Window's ADO object:
# OLEDB PROVIDER
import adodbapi
conn = adodbapi.connect("PROVIDER=Microsoft.ACE.OLEDB.12.0;" \
"Data Source = C:\\Test1.xlsx;" \
"Extended Properties ='Excel 12.0 Xml;HDR=YES'")
cursor = conn.cursor()
cursor.execute("SELECT * FROM [Orders$]")
for row in cursor.fetchall():
print(row)
# ODBC DRIVER
import pyodbc
conn = pyodbc.connect("DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};" \
"DBQ=C:\Path\To\Excel.xlsx;")
cursor = conn.cursor()
cursor.execute("SELECT * FROM [Orders$]")
for row in cursor.fetchall():
print(row)
I am trying to move data from a database I own to a database I only have read/write permissions on (as a temp table). However, I get an error. Please see the below code:
import pandas as pd
import pyodbc
import sqlalchemy
con = pyodbc.connect(r'Driver={SQL Server};Server=MYServer;Database=DB_People;Trusted_Connection=yes;)
sSQL = "SELECT * FROM tbl_People;"
df = pd.read_sql(sSQL, con)
con.close()
con = pyodbc.connect(r'Driver={SQL Server};Server=NOT_MyServer;Database=DB_People;Trusted_Connection=yes;)
sSQL = "CREATE TABLE [##People Table] (p_Name varchar(25), p_DOB char(10));"
con.execute(sSQL)
con.committ()
engine = sqlalchemy.create_engine('mssql://NOT_MyServer/DB_People?Driver=SQL+Server+Native+Client+11.0?trusted_connection=yes')
df.to_sql("##People Table")
I get the error:
DBAPIError: (pyodbc.Error) ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
Any clues as to what the issue is? I specified a Driver in my connection and I know the Temp table exists because when I connect via SSMS I can query the table (although there are no records at this point.
I
It seems as if I have found the problem(s):
The "Create Table" function is unneeded as the df.to_sql creates the table
Instead of the "+" in the Driver name, I was able to replace them with %20
This worked for me.