1
votes

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?

1
Indenting is really important in python, and your example code is full of crappy indenting. Fix that first and try then again.James Z

1 Answers

1
votes

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)