Error while importing python o/p to ms access - python

code I used to establish connection between python code and ms-access
import pyodbc
conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=D:\LnT_project\Project.accdb;')
cursor = conn.cursor()
cursor.execute("Insert into dbtable (File_name, File_size) values(abc, 2)")
conn.commit()
I am getting this error:
pyodbc.Error: ('07002', '[07002] [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 2. (-3010) (SQLExecDirectW)')

Try with quotes to mark as a text value:
cursor.execute("Insert into dbtable (File_name, File_size) values('abc', 2)")

Related

How to do df.to_sql using SQL Server in Azure

I can do a df.to_slq on my local instance of SQL Server just fine. I am getting stuck when trying to do the same df.to_sll using Python and Azure SQL Server. I thought it would essentially be done like this.
import urllib.parse
params = urllib.parse.quote_plus(
'Driver=%s;' % '{ODBC Driver 17 for SQL Server}' +
'Server=%s,1433;' % 'ryan-server.database.windows.net' +
'Database=%s;' % 'ryan_sql_db' +
'Uid=%s;' % 'UN' +
'Pwd={%s};' % 'PW' +
'Encrypt=no;' +
'TrustServerCertificate=no;'
)
from sqlalchemy.engine import create_engine
conn_str = 'mssql+pyodbc:///?odbc_connect=' + params
engine = create_engine(conn_str)
connection = engine.connect()
connection
all_data.to_sql('health', engine, if_exists='append', chunksize=100000, method=None,index=False)
That is giving me this error.
OperationalError: (pyodbc.OperationalError) ('08S01', '[08S01] [Microsoft][ODBC Driver 17 for SQL Server]TCP Provider: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.\r\n (10060) (SQLExecDirectW); [08S01] [Microsoft][ODBC Driver 17 for SQL Server]Communication link failure (10060)')
[SQL: INSERT INTO health ([0], [Facility_BU_ID], [Code_Type], [Code], [Description], [UB_Revenue_Code], [UB_Revenue_Description], [Gross_Charge], [Cash_Charge], [Min_Negotiated_Rate], [Max_Negotiated_Rate], etc., etc., etc.
I found this link today:
https://learn.microsoft.com/en-us/sql/machine-learning/data-exploration/python-dataframe-sql-server?view=sql-server-ver15
I tried to do something similar, like this.
import pyodbc
import pandas as pd
df = all_data
# server = 'myserver,port' # to specify an alternate port
server = 'ryan-server.database.windows.net'
database = 'ryan_sql_db'
username = 'UN'
password = 'PW'
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
# Insert Dataframe into SQL Server:
for index, row in df.iterrows():
cursor.execute(all_data.to_sql('health', cnxn, if_exists='append', chunksize=100000, method=None,index=False))
cnxn.commit()
cursor.close()
When I run that, I get this error.
DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': ('42S02', "[42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'sqlite_master'. (208) (SQLExecDirectW); [42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared. (8180)")
What I'm really hoping to to is df.to_sql, not Insert Into. I am working in Spyder and trying to send the data from my local machine to the cloud.
I read the two links below, and got it working.
https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-set-database-firewall-rule-azure-sql-database?view=azuresqldb-current
https://www.virtual-dba.com/blog/firewalls-database-level-azure-sql/
Basically, you need to open your command window on your local machine, enter 'ipconfig', and grab two IP addresses. Then, enter those into SQL Server in Azure.
EXECUTE sp_set_database_firewall_rule
N'health',
'192.0.1.1',
'192.0.0.5';
Finally, run the small script below, in SQL Server, to confirm that the changes were made correctly.
USE [ryan_sql_db]
GO
SELECT * FROM sys.database_firewall_rules
ORDER BY modify_date DESC

Python to Access connection Database Error?

I am looking to connect python to an Access database with the following code:
connStr = (
r"DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};"
r"DBQ=O:\Architecture\DAART\Data Analytics Team\DAART.accdb;"
)
cnxn = pyodbc.connect(connStr)
cursor = cnxn.cursor()
df = pd.read_sql("select * from APMS SV-8 Report", cnxn)
For the last line of code, I am receiving the following error message:
DatabaseError: Execution failed on sql 'select * from APMS SV-8 Report': ('42000', '[42000] [Microsoft][ODBC Microsoft Access Driver] Syntax error in FROM clause. (-3506) (SQLExecDirectW)')
Access SQL requires you bracket table names if they contain spaces, keywords or special characters:
select * from [APMS SV-8 Report]

Connect python with SQL Server

I'm trying to load to the memory a table which is on a SQL Server database, but keep getting an error.
I coded:
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
'Server=DESKTOP-VCIBA22\MS_SQL_SERVER;'
'Database=BikeStores;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('SELECT * FROM BikeStores.staffs')
and received the following error:
pyodbc.ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC SQL
Server Driver][SQL Server]Invalid object name 'BikeStores.staffs'.
(208) (SQLExecDirectW)")
Any ideas?
Thanks!

Connecting through pyodbc, strange error

I'm getting the following error after running this:
connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=xxxxx.xxxx.net;PORT=1443;DATABASE=xxx;UID=xxxx;PWD=xxxx')
cursor = connection.cursor()
SQLCommand = ("SELECT [Date]...FROM [dbo].[...]")
cursor.execute(SQLCommand)
results = cursor.fetchone()
connection.close
Error: libc++abi.dylib: terminating with uncaught exception of type std::runtime_error: collate_byname::collate_byname failed to construct for C/en_US.UTF-8/C/C/C/C
Any ideas on how to remediate?

Server does not exist or access denied

I have written below code to connect SQL Server Database from Visual Studio using Python:
import pyodbc
con = pyodbc.connect('Driver={SQL Server};Server=localhost;Database=ReportServerTempDB;Trusted_Connection=yes')
cur = con.cursor()
cur.execute("select [User], [datetime] FROM [ReportServerTempDB].[dbo].
[DBUpgradeHistory]")
for row in cur:
print (row.user + "," + row.datetime)
#print row[0] + "," + row[1]
cur.close()
con.close()
However, I'm getting an error like this:
Traceback (most recent call last):File "IronPythonApplication1.py",
line 2,in con = pyodbc.connect('Driver={SQL
Server};Server=localhost;Database=ReportServerTempDB;Trusted_Connection=yes')
pyodbc.Error: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver]
[DBNETLIB]SQL Server does not exist or access denied. (17)
(SQLDriverConnect)')
Note: I have Windows Authentication to SQL Server, and I'm using VS 2015, and Python environment is IRON Python 64 bit 2.7
EDIT:
I changed driver as this: Driver={ODBC Driver 11 for SQL Server}
If I give like this in my code
for row in cur:
print (row.user)
getting a new kind of error.
Traceback (most recent call last):
File "IronPythonApplication1.py", line 6, in
for row in cur:
pyodbc.ProgrammingError: Attempt to use a closed cursor.
How to solve this?
I just changed it like this and its working:
import pyodbc
con = pyodbc.connect('Driver={ODBC Driver 11 for SQL Server};Server=localhost;Database=ReportServer;Trusted_Connection=yes')
cur = con.cursor()
cur.execute("select userid,username from Users")
for row in cur.fetchall():
print (row)

Categories

Resources