SQL Server e Python

L’integrazione tra .NET e SQL Server è data per scontata: in questo articolo esploreremo invece  come accedere a SQL Server da Python. Uno dei vantaggi di python è che è un linguaggio molto facile da imparare, con un notevole numero di librerie e un’ottima integrazione multi piattaforma. Oltre a ciò python offre un sistema di installazione rapido delle librerie (come  Ruby e Perl).

Pyodbc: introduzione

Vi sono parecchie librerie odbc/SQLServer per python. Abbiamo deciso di presentare pyodbc.
Da Windows, potete installare pyodbc nel seguente modo:
[bash]$easy_install pyodbc
Searching for pyodbc
Reading http://pypi.python.org/simple/pyodbc/
Reading http://code.google.com/p/pyodbc
Reading http://code.google.com/p/pyodbc/downloads/list
Best match: pyodbc 2.1.8
Downloading http://pyodbc.googlecode.com/files/pyodbc-2.1.8.win32-py2.6.exe
Processing pyodbc-2.1.8.win32-py2.6.exe
creating ‘c:\docume~1\giorgig\impost~1\temp\easy_install-53xdpl\pyodbc-2.1.8-py2.6-win32.egg’ and adding ‘c:\docume~1\giorgig\impost~1\temp\
easy_install-53xdpl\pyodbc-2.1.8-py2.6-win32.egg.tmp’ to it
Moving pyodbc-2.1.8-py2.6-win32.egg to c:\python26\lib\site-packages
Adding pyodbc 2.1.8 to easy-install.pth file

Installed c:\python26\lib\site-packages\pyodbc-2.1.8-py2.6-win32.egg
Processing dependencies for pyodbc
Finished processing dependencies for pyodbc[/bash]
Poi seguendo un semplice esempio, ecco come scoprire la somma di due numeri…
[python]cs=r’DRIVER={SQL Server};SERVER=mypc\SQLEXPRESS;DATABASE=test1;UID=test1;PWD=test1′;
cnxn = pyodbc.connect(cs);
cursor = cnxn.cursor();
cursor.execute("SELECT 1+2");
print(str(cursor.fetchone()));[/python]
Al momento non sembra esistere un modo semplice per connettersi alla versione embedded (compact) di SQL. Risulta molto comoda però l’integrazione con Excel, con sintassi del tipo:
[python]pyodbc.connect("Driver={Microsoft Excel Driver (*.xls)}; Dbq=Sample.xls", autocommit=True)[/python]
Conclusioni e letture ulteriori

Con la seguente libreria è possibile integrare python django e sql server.