上一篇文章,咱們寫到如何在centos7.5 安裝sql server數據庫,這篇來講明下如何使用python鏈接sql server數據庫並完成數據庫操做。python
1、環境準備sql
操做系統:centos7.5 x64數據庫
安裝包:pyodbc-2.1.7(或者pymssql,該模塊須要安裝依賴較多,不建議)離線安裝使用rpm包安裝,在線安裝直接運行:pip install pyodbc rpm包下載地址:https://download.csdn.net/download/hu_wen/11275091centos
python環境:python2.7 或者python3以上python2.7
安裝完成pyodbc需修改配置文件 /etc/odbcinst.ini 新增如下內容:fetch
[SQL Server]
Description = FreeTDS ODBC driver for MSSQL
Driver = /usr/lib64/libtdsodbc.so
Setup = /usr/lib64/libtdsS.so.2
FileUsage = 1centos7
配置完成後便可調試python代碼進行鏈接,如下是事例代碼:操作系統
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import pyodbc
#建立數據庫鏈接
conn = pyodbc.connect("DRIVER={SQL Server};SERVER=192.168.142.11,1433;DATABASE=master;UID=sa;PWD=hu_wen@2019")
cursor = conn.cursor() # 獲取光標
# 建立表
cursor.execute("""
IF OBJECT_ID('persons', 'U') IS NOT NULL
DROP TABLE persons
CREATE TABLE persons (
id INT NOT NULL,
name VARCHAR(100),
salesrep VARCHAR(100),
PRIMARY KEY(id)
)
""")
# 插入多行數據
cursor.executemany(
"INSERT INTO persons VALUES (%d, '%s', '%s')",
[(1, 'John Smith', 'John Doe'),
(2, 'Jane Doe', 'Joe Dog'),
(3, 'Mike T.', 'Sarah H.')])
# 提交數據
conn.commit()
# 查詢數據
cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')
# 遍歷數據(存放到元組中) 方式1
row = cursor.fetchone()
while row:
print("ID=%d, Name=%s" % (row[0], row[1]))
row = cursor.fetchone()
# 遍歷數據(存放到元組中) 方式2
for row in cursor:
print('row = %r' % (row,))
# 關閉鏈接
conn.close()
如調試過程當中遇到問題,歡迎留言交流!
--------------------- .net