欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python连接Mssql基础教程之Python库pymssql

程序员文章站 2023-01-19 10:14:02
前言 pymssql模块是用于sql server数据库(一种数据库通用接口标准)的连接。另外pyodbc不仅限于sql server,还包括oracle,mysql,a...

前言

pymssql模块是用于sql server数据库(一种数据库通用接口标准)的连接。另外pyodbc不仅限于sql server,还包括oracle,mysql,access,excel等。

另外除了pymssql,pyodbc还有其他几种连接sql server的模块,感兴趣的可以在这里找到:https://wiki.python.org/moin/sql%20server

本文将详细介绍关于python连接mssql之python库pymssql的相关内容,下面话不多说了,来一起看看详细的介绍吧

连接数据库

pymssql连接数据库的方式和使用sqlite的方式基本相同:

  • 使用connect创建连接对象
  • connect.cursor创建游标对象,sql语句的执行基本都在游标上进行
  • cursor.executexxx方法执行sql语句,cursor.fetchxxx获取查询结果等
  • 调用close方法关闭游标cursor和数据库连接
import pymssql

# server  数据库服务器名称或ip
# user   用户名
# password 密码
# database 数据库名称
conn = pymssql.connect(server, user, password, database)

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.')])
# 如果没有指定autocommit属性为true的话就需要调用commit()方法
conn.commit()

# 查询操作
cursor.execute('select * from persons where salesrep=%s', 'john doe')
row = cursor.fetchone()
while row:
  print("id=%d, name=%s" % (row[0], row[1]))
  row = cursor.fetchone()

# 也可以使用for循环来迭代查询结果
# for row in cursor:
#   print("id=%d, name=%s" % (row[0], row[1]))

# 关闭连接
conn.close()

注意: 例子中查询操作的参数使用的%s而不是'%s',若参数值是字符串,在执行语句时会自动添加单引号

游标使用注意事项

一个连接一次只能有一个游标的查询处于活跃状态,如下:

c1 = conn.cursor()
c1.execute('select * from persons')

c2 = conn.cursor()
c2.execute('select * from persons where salesrep=%s', 'john doe')

print( "all persons" )
print( c1.fetchall() ) # 显示出的是c2游标查询出来的结果

print( "john doe" )
print( c2.fetchall() ) # 不会有任何结果

为了避免上述的问题可以使用以下两种方式:

  • 创建多个连接来保证多个查询可以并行执行在不同连接的游标上
  • 使用fetchall方法获取到游标查询结果之后再执行下一个查询, 如下:
c1.execute('select ...')
c1_list = c1.fetchall()

c2.execute('select ...')
c2_list = c2.fetchall()

游标返回行为字典变量

上述例子中游标获取的查询结果的每一行为元组类型,

可以通过在创建游标时指定as_dict参数来使游标返回字典变量,

字典中的键为数据表的列名

conn = pymssql.connect(server, user, password, database)
cursor = conn.cursor(as_dict=true)

cursor.execute('select * from persons where salesrep=%s', 'john doe')
for row in cursor:
 print("id=%d, name=%s" % (row['id'], row['name']))

conn.close()

使用with语句(上下文管理器)

可以通过使用with语句来省去显示的调用close方法关闭连接和游标

with pymssql.connect(server, user, password, database) as conn:
 with conn.cursor(as_dict=true) as cursor:
  cursor.execute('select * from persons where salesrep=%s', 'john doe')
  for row in cursor:
   print("id=%d, name=%s" % (row['id'], row['name']))

调用存储过程

pymssql 2.0.0以上的版本可以通过cursor.callproc方法来调用存储过程

with pymssql.connect(server, user, password, database) as conn:
 with conn.cursor(as_dict=true) as cursor:
  # 创建存储过程
  cursor.execute("""
  create procedure findperson
   @name varchar(100)
  as begin
   select * from persons where name = @name
  end
  """)

  # 调用存储过程
  cursor.callproc('findperson', ('jane doe',))
  for row in cursor:
   print("id=%d, name=%s" % (row['id'], row['name']))

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。

参考:http://pymssql.org/en/stable/pymssql_examples.html