Python - Connect to SQL Server DB Example


pyodbc is an open source Python extension module that makes access to ODBC databases easier.
It implements the DB API 2.0 specification but is packed with even more Pythonic convenience.

pyodbc can be downloaded from htts://pypi.python.org/pypi/pyodbc

However, the fastest and easiest way to install pyodbc is with pip:
pip install pyodbc


sql_server_example1.py

import pyodbc
connection = pyodbc.connect('Driver={SQL Server};Server=localhost;Database=testdb;Trusted_Connection=yes'))

cursor = connection.cursor()
cursor.execute('select empno,ename,job,sal,deptno from emp order by deptno,ename')

 

print("empno \t ename\t\t job \t\t sal \t\t deptno \t")

print("===== \t ======\t\t ========== \t ====== \t ====== \t")

for empno, ename, job, sal, deptno in cursor:   
print(str(empno).ljust(8),ename.ljust(15),job.ljust(15),
      str(sal).ljust(15),str(deptno).ljust(15))

 

cursor.close()

connection.close()

 

Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 16:02:32) [MSC v.1900 64 bit (AMD64)] on win32

Type "copyright", "credits" or "license()" for more information.

>>> 

===== RESTART: C:\\Python-Know-how\sql_server_example1.py =====

 

 

 

[Reference]
https://mkleehammer.github.io/pyodbc/

 

 

 

arrow
arrow
    文章標籤
    Python SQL Server
    全站熱搜

    DanBrother 發表在 痞客邦 留言(0) 人氣()