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)
Related
Here is my code. I'm trying to insert data from a CSV into a SQL Server Table. I'm trying to follow what seems like a relatively simple example here:
https://datatofish.com/import-csv-sql-server-python/
import pandas as pd
import pyodbc
data = pd.read_csv(r'C:\Users\Steve\Documents\Datasets\covidgeography.csv')
df = pd.DataFrame(data, columns=['MMSA', 'total_percent_at_risk', 'high_risk_per_ICU_bed', 'high_risk_per_hospital',
'icu_beds', 'hospitals', 'total_at_risk'])
print(df)
conn = pyodbc.connect('Driver={SQL Server};'
'Server=STEVELAPTOP;'
'Database=AdventureWorks2017;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
#cursor.execute('CREATE TABLE dbo.covidgeo(MMSA nvarchar(250),total_percent_at_risk nvarchar(250),'
# 'high_risk_per_ICU_bed nvarchar(250), '
# 'high_risk_per_hospital nvarchar(250),icu_beds nvarchar(250),hospitals nvarchar(250),total_at_risk '
# 'nvarchar(250))')
for row in df.itertuples():
cursor.execute('''INSERT INTO AdventureWorks2017.dbo.covidgeo(MMSA,total_percent_at_risk,high_risk_per_ICU_bed,
high_risk_per_hospital,icu_beds,hospitals,total_at_risk) VALUES (???????)
''',
row.MMSA,
row.total_percent_at_risk,
row.high_risk_per_ICU_bed,
row.high_risk_per_hospital,
row.icu_beds,
row.hospitals,
row.total_at_risk)
conn.commit()
After I run this I get this error:
Traceback (most recent call last):
File "C:\Users\Steve\PycharmProjects\DataLearning\DataImport.py", line 20, in <module>
cursor.execute('''INSERT INTO AdventureWorks2017.dbo.covidgeo(MMSA,total_percent_at_risk,high_risk_per_ICU_bed,
pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Must declare the scalar variable "#P1#P2#P3#P4#P5#P6#P7". (137) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared. (8180)')
Do I have a syntax error in how I'm writing the insert statement?
It was a syntax error. I had to change:
VALUES (???????)
to
VALUES (?,?,?,?,?,?,?)
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]
I'm trying to connect to SQL Server 2017 Express via Python and tried the following code:
conn = pyodbc.connect('Driver={SQL Server};'
'Server=USYD1WCXS3\SQLEXPRESS;'
'Database= tempdb;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('SELECT * FROM db_name.tablename')
for row in cursor:
print(row)
I also tried the following:
conn = pyodbc.connect('Driver={SQL Server Native Client 17.0};'
'Server=USYD1WCXS3\SQLEXPRESS;'
'Database= tempdb;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('SELECT * FROM db_name.tablename')
for row in cursor:
print(row)
and
conn = pyodbc.connect('Driver={ODBC Driver 17 for SQL Server};'
'Server=USYD1WCXS3\SQLEXPRESS;'
'Database= tempdb;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('SELECT * FROM db_name.tablename')
for row in cursor:
print(row)
This is the error I am getting every time
InterfaceError
Traceback (most recent call last)
in
1 import pyodbc
2 conn = pyodbc.connect('Driver={SQL Server Native Client 17.0};'
3 'Server=USYD1WCXS3\SQLEXPRESS;'
4 'Database= tempdb;'
5 'Trusted_Connection=yes;')
InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
I am very new to python and SQL. I have a DB query in Excel which is very large that I am trying to move to Python directly. Currently i read it in from excel using read_excel().
Ive installed import pyodbc and tried to take the connection string from excel and put it into python.
default code that i have written is:
import pyodbc
conn_str = 'Provider.....'
conn = pyodbc.connect(conn_str)
SQL_Query = pd.read_sql_query(
'''SELECT *
FROM [MarketData].[Gas].[KplerVesselHistory]''', conn)
The excel connection info is as follows:
Connection type: OLE DB Query
Connection string: Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=MarketData;Data Source=FOTDAL02PR;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=[blank];Use Encryption for Data=False;Tag with column collation when possible=False
Command type: SQL
The error I'm getting is:
Traceback (most recent call last):
File "C:\dev\bin\pycharm\helpers\pydev\_pydevd_bundle\pydevd_exec2.py", line 3, in Exec
exec(exp, global_vars, local_vars)
File "<string>", line 3, in <module>
pyodbc.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
Something like this might work:
This connects using the ODBC driver for SQL Server, runs the query and returns it to Pandas DataFrame and then prints the output.
import pyodbc
import pandas
driver = '{ODBC Driver 17 for SQL Server}'
server = 'server_name\instance_name'
database = 'MarketData'
sql = 'SELECT * FROM [MarketData].[Gas].[KplerVesselHistory]'
conn_str = 'Driver={};Server={};Trusted_Connection=True;Database={}'.format(driver, server, database)
conn = pyodbc.connect(conn_str)
df = pandas.read_sql(sql, conn)
print(df)
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?