How do I create a copy of a table using PYODBC? - python

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)

Related

Unable To Connect mdb VIEW Table via pyodbc Python

I am now facing a difficulty connecting VIEW table in mdb file using pyodbc.
Current code is as follows:
(Previous Provider: Microsoft.Jet.OLEDB.4.0)
import pyodbc
pyodbc.pooling = False
conn_str = (
r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};'
r'DBQ=C:***.mdb;'
)
cnxn = pyodbc.connect(conn_str)
crsr = cnxn.cursor()
for table_info in crsr.tables(tableType='TABLE'):
print(table_info.table_name)
strSQL = "SELECT A,B FROM tableC WHERE ** ORDER BY B"
crsr.execute(strSQL)
for row in crsr.fetchall():
print(row)
When it works, for table_info in crsr.tables(tableType='TABLE'): seems to have no issue.
This is because print(table_info.table_name) displays several table names.
However, when crsr.execute(strSQL) is done, exeption error has raised and following message
('HY000', "[HY000] [Microsoft][ODBC Microsoft Access Driver] ODBC--connection to 'VIEW' failed. (-2001) (SQLExecDirectW)")
is shown.
It would be appreciated to instruct me how to overcome this issue.
Thanks.

Setting Default value for column in MS access using sql query in Python [duplicate]

I'm trying to add a column to an MS Access database table using pyodbc and Python 3.5.
Using the expression
self.cursor.execute("ALTER TABLE data ADD COLUMN testColumn TEXT(10)")
works fine, but when I try to add a default value (DEFAULT "no"), it throws a Syntax error. I've tried multiple combinations, but no luck.
Any help is much appreciated!
Cheers
Sadly, the Access ODBC driver simply does not support the DEFAULT clause for a column in CREATE/ALTER TABLE statements. The ODBC driver and OLEDB provider for Access have diverged somewhat in their DDL support, so unfortunately we can get inconsistent results for the same DDL statement as illustrated by the following VBScript code using ADO:
OLEDB works fine ...
Option Explicit
Dim conn
Set conn = CreateObject("ADODB.Connection")
Dim connStr
connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Public\mdbTest.mdb"
conn.Open connStr
On Error Resume Next
conn.Execute "DROP TABLE Cheeses"
On Error GoTo 0
conn.Execute "CREATE TABLE Cheeses (Id LONG PRIMARY KEY, CheeseName TEXT(50) DEFAULT 'Cheddar')"
conn.Execute "INSERT INTO Cheeses (Id) VALUES (1)"
Dim rst
Set rst = CreateObject("ADODB.Recordset")
rst.Open "SELECT CheeseName FROM Cheeses WHERE Id = 1", conn
If rst("CheeseName").Value = "Cheddar" Then
WScript.Echo "Success"
End If
conn.Close
... but if we change the connection string to use ODBC ...
connStr = "Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=C:\Users\Public\mdbTest.mdb"
... then our attempt to execute the CREATE TABLE statement fails with
Microsoft OLE DB Provider for ODBC Drivers: [Microsoft][ODBC Microsoft Access Driver] Syntax error in CREATE TABLE statement.
TL;DR - You can't use the DEFAULT clause in a CREATE/ALTER TABLE statement under pyodbc.

Why is this Python error code: Too Few parameters. Expected1. (-3010) occurring when using pyodbc?

I am writing a python script that executes some SQL code however whenever I call the function containing this SQL it gives me the error:
File "Z:/ ... /Script.py", line 40, in Function
cnxn.execute("""INSERT INTO Table1 VALUES (007, Bond);""")
Error: ('07002', '[07002] [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1. (-3010) (SQLExecDirectW)')
I have researched this problem and found other posts with the same error but I can't seem to apply the answers given to my code. For example:
facing Too few parameters. Expected 1. (-3010) (SQLExecDirectW)')" error in python program
import pyodbc
conn_str = (
r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};'
r'DBQ=Z:\ ... \DB.accdb;'
)
cnxn = pyodbc.connect(conn_str)
crsr = cnxn.cursor()
cnxn.execute("""INSERT INTO Table1 VALUES (007, Bond);""")
I originally had only single quotes and tried what Navnath said in his answer and use triple quotes but that changed nothing. I believe that my SQL syntax is correct so I don't understand why this approach isn't working and why this error is coming up. Any help would be greatly appreciated!
Your problem seems to be that you're running the .execute() method from the connection rather than from the cursor you have opened. Also, it's always better to be explicit and use bound variables. Try this?
import pyodbc
conn_str = (
r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};'
r'DBQ=Z:\ ... \DB.accdb;'
)
cnxn = pyodbc.connect(conn_str)
crsr = cnxn.cursor()
crsr.execute(
"""
INSERT INTO Table1 (agent_number, agent_last_name) VALUES (?, ?)
""",
('007', 'Bond')
)
Depending on your connection, you may also need to do a .commit() afterwards, since you're inserting, updating, or deleting data. Good luck!

SQLAlchemy df.to_sql MSSQL

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.

Function sequence error in PYODBC

I am using pyodbc to connect to a database and extract certain data from it.
Here is my code:
con = pyodbc.connect("driver={SQL Server};server= MyServer;database= MyDatabase;trusted_connection=true")
cursor = con.cursor()
SQL_command = """
SELECT RowID = ISNULL
(
(
SELECT TOP 1 RowID
FROM [MyDatabase].[admin].[MyTable]
WHERE [queue] = ? and processed IS NULL
)
,-1
)
"""
cursor.execute(SQL_command, queueNumber)
cursor.commit()
con.commit()
result_set = cursor.fetchall()
And I got following error after I run above code:
pyodbc.Error: ('HY010', '[HY010] [Microsoft][ODBC SQL Server
Driver]Function sequence error (0) (SQLFetch)')
May I know what caused such problem, and how can I fix it?
Thanks.
I believe your problem is the strange commit statements. You only need to commit when inserting or updating records not selecting.
cursor.execute(SQL_command, queueNumber)
result_set = cursor.fetchall()
Also, in the future when using commit, both cursor.commit and con.commit do the same thing, you only need one.
Finally, I'd get used to calling execute with the second arguement as a tuple:
cursor.execute(SQL_command, (queueNumber,))
The way you have it works for pyodbc but is not DB API standard.
I was recieving the two following errors more or less interchangeably:
pyodbc.Error: ('HY010', '[HY010] [Microsoft][ODBC Driver 17 for SQL Server]Function sequence error (0) (SQLGetData)')
pyodbc.Error: ('HY007', '[HY007] [Microsoft][ODBC Driver 17 for SQL Server]Associated statement is not prepared (0) (SQLNumResultCols)')
My problem was, that two threads were using the same connection, which led to weird states of the prepared statements. I fixed it by creating a new connection for each thread.

Categories