To summarize the connection process, I'm trying to create a function to connect the database, but I'm not able to make the connection as expected:
def conectar_com_banco(usuario):
if usuario in 'illuminati':
username = 'illuminati'
password = 'fnord'
elif usuario in 'fascist_firewall':
username = 'tor'
password = 'onion'
else:
print('usuario_nao_encontrado')
import pyodbc
cnxn = pyodbc.connect('DRIVER = SQL Server; SERVER = conspiracy; DATABASE = illuminati; UID='+username+';PWD='+password)
cnxn.cursor()
return(cursor)
cursor=conectar_com_banco('illu')
cursor.execute("SELECT @@version;")
row = cursor.fetchone()
print(row)
When I run this code, I get the following response:
Traceback (most recent call last):
File "<ipython-input-4-d96fceb45081>", line 18, in <module>
cursor=conectar_com_banco('illu')
File "<ipython-input-4-d96fceb45081>", line 14, in conectar_com_banco
cnxn = pyodbc.connect('DRIVER = SQL Server; SERVER = conspiracy; DATABASE = illuminati; UID='+username+';PWD='+password)
InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Nome da fonte de dados não encontrado e nenhum driver padrão especificado (0) (SQLDriverConnect)')
When the correct answer would be the version of my database as it does in the reference: #
Resolution:
The error occurred in:
cnxn = pyodbc.connect('DRIVER = SQL Server; SERVER = conspiracy; DATABASE = illuminati; UID='+username+';PWD='+password)
So I rewrote as follows:
def conectar_com_banco(usuario):
if usuario in 'illuminati':
server = 'conspiracy'
database = 'illuminati'
username = 'illuminati'
password = 'fnord'
elif usuario in 'fascist_firewall':
server = 'conspiracy'
database = 'illuminati'
username = 'tor'
password = 'onion'
else:
print('funcao_nao_encontrado')
import pyodbc
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cur=cnxn.cursor()
return(cur)
cursor=conectar_com_banco('illu')
cursor.execute("SELECT @@version;")
row = cursor.fetchone()
print(row)
And I got back the expected:
('Microsoft SQL Server 2005 - 9.00.5000.00 (X64) \n\tDec 10 2010 10:38:40 \n\tCopyright (c) 1988-2005 Microsoft Corporation\n\tEnterprise Edition (64-bit) on Windows NT 6.1 (Build 7601: Service Pack 1)\n', )
I have not yet figured out which syntax error I should have committed.
PS: Both {ODBC Driver 13 for SQL Server} and {SQL Server} worked.