安装

pip install pymssql

 

连接数据库 pymssql.connect()

# coding:utf-8

import pymssql

server = '192.168.8.1' #服务器ip或名称
user = 'sa' #用户名
password = '111111'  #密码
database = 'test' #数据库

dbconnect = pymssql.connect(server = server,user = user,password=password,database = database) #连接到数据库

 

操作数据库 connect.cursor()  ,

fetchone() 取一行

fetchall() 取所有结果

dbcursor = dbconnect.cursor() #游标
dbcursor.execute('select top 2 name,major from test_student') 

#一行一行的取数
row = dbcursor.fetchone()
print(row)
row = dbcursor.fetchone()
print(row)
row = dbcursor.fetchone() #取完数据,None
print(row)

 

python入门22  pymssql模块(python连接sql server查询)

 

#取出所有查询结果
rows = dbcursor.fetchall() print(rows) # list

rows = dbcursor.fetchall() #再取空
print(rows) # []
 

python入门22  pymssql模块(python连接sql server查询)

 

游标加上 as_dict=True。结果显示dict
dbcursor = dbconnect.cursor() #游标
dbcursor.execute('select top 10 name,major from test_student')
print(dbcursor.fetchall())

python入门22  pymssql模块(python连接sql server查询)

dbcursor = dbconnect.cursor(as_dict=True) #游标
dbcursor.execute('select top 10 name,major from test_student')
print(dbcursor.fetchall())

python入门22  pymssql模块(python连接sql server查询)

 

 

最后记得关闭游标和连接

dbcursor.close()
dbconnect.close()

 

官网: http://pymssql.org/en/stable/ 

 

相关文章:

  • 2021-11-23
  • 2022-12-23
  • 2021-12-18
  • 2021-12-08
  • 2021-10-26
  • 2022-02-10
  • 2021-05-18
猜你喜欢
  • 2022-01-20
  • 2021-07-18
  • 2021-11-04
  • 2022-02-17
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案