[Pyhton]连接MSSQL实例并执行SQL语句

运行环境:

服务器端:
MSSQL 2014
Server 2012 R2

程序端:
Python 3.7.4
MacOS 10.14.6
CentOS Linux release 7.7.1908 (Core)

程序代码

#!/usr/bin/env pyhton
# coding:utf-8
# @Time     : 2020-02-13 09:08
# @Author   : LeoShi
# @Site     : 
# @File     : connect_mssql.py
# @Software : MacOS Python 3.7

import pyodbc
import time

# 建立MSSQL服务器连接的信息
server = '172.16.1.101'
database = 'student'
uid = 'SA'
pwd = 'Abcd1234'
driver = 'ODBC Driver 17 for SQL Server'
con_string = f'DRIVER={driver};SERVER={server};DATABASE={database};UID={uid};PWD={pwd}'
# 建立连接
sql_connect = pyodbc.connect(con_string)
sql_connect.autocommit = True
# 设置游标
sql_cursor = sql_connect.cursor()
# 执行SQL语句(查询数据库文件位置及名称)
sql_cursor.execute('select * from student.dbo.student;')
# 获得语句执行后的结果
result = sql_cursor.fetchall()
print(type(result))
print(result)
# 执行SQL语句
sql_connect.commit()

time.sleep(5)
sql_cursor.close()
sql_connect.autocommit = False
sql_connect.close()

#----运行结果------

<class 'list'>
[('120001', '张三', '', 18, '云南省昆明市五华区', None, None), ('120002', '李四', None, None, None, None, '计算机科学与技术')]

 

posted @ 2020-02-13 12:57  LeoShi2020  阅读(335)  评论(0编辑  收藏  举报