pymssql包是Python语言用于连接SQL Server数据库的驱动程序(或者称作DB API),它是最终和数据库进行交互的工具。SQLAlchemy包就是利用pymssql包实现和SQL Server数据库交互的功能的。

一,pymssql包的基本组成

pymssql包有两个模块构成:pymssql 和 _mssql,pymssql 是建立在_mssql模块之上的模块。

pymssql模块由Connection和Cursor 两个大类构成:

  • Connection类代表MS SQL Sever数据库的一个连接,
  • Cursor类用于向数据库发送查询请求,并获取查询的的结果。

二,连接

连接对象用于连接SQL Server引擎,并设置连接的属性,比如连接超时,字符集等。

1,创建连接对象

pymssql通过类函数来构建连接对,在创建连接对象的同时,打开连接:

class pymssql.Connection(user, password, host, database, timeout, login_timeout, charset, as_dict)

2,构建Cursor对象

在创建连接对象之后,创建Cursor对象,使用Cursor对象向数据库引擎发送查询请求,并获取查询的结果:

Connection.cursor(as_dict=False)

as_dict是布尔类型,默认值是False,表示返回的数据是元组(tuple)类型;如果设置为True,返回的数据集是字典(dict)类型。

3,提交查询和自动提交模式

在执行查询之后,必须提交当前的事务,以真正执行Cursor对象的查询请求:

Connection.commit()

默认情况下,自动提交模式是关闭的,用户可以设置自动提交,pymssql自动执行Cursor发送的查询请求:

Connection.autocommit(status)

status是bool值,True表示打开自动提交模式,False表示关闭自动提交模式,默认值是False。

4,关闭连接

在执行完查询之后,关闭连接:

Connection.close()

三,Cursor

通过打开的连接对象来创建Cursor对象,通过Cursor对象向数据库引擎发送查询请求,并获取查询的结果。

1,执行查询

Cursor对象调用execute**()函数来执行查询请求,

Cursor.execute(operation)
Cursor.execute(operation, params)
Cursor.executemany(operation, params_seq)

参数注释:

  • operation:表示执行的sql语句,
  • params :表示sql语句的参数,
  • params_seq:参数序列,用于sql语句包含多个参数的情况。

注意,除设置自动提交模式之外,必须在执行查询之后,通过连接对象来提交查询。

Connection.commit()

如果sql语句只包含一个参数,那么必须在sql语句中显式使用%s或%d作为占位符,分别用于引用字符型的参数和数值型的参数。

cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')

如果sql语句包含多个参数,那么使用list来传递参数:

cursor.executemany(
"INSERT INTO persons VALUES (%d, %s, %s)",
[(1, 'John Smith', 'John Doe'),
(2, 'Jane Doe', 'Joe Dog'),
(3, 'Mike T.', 'Sarah H.')])

2,获取查询结果

Cursor对象调用fetch**()函数来获取查询的结果:

Cursor.fetchone()
Cursor.fetchmany(size=None)
Cursor.fetchall()

fetch**()函数是迭代的:

  • fetchone():表示从查询结果中获取下一行(next row)
  • fetchmany():表示从查询结果中获取下面的多行(next batch)
  • fetchall():表示从查询结果中获取剩余的所有数据行(all remaining)

3,跳过结果集

当查询的结果包含多个结果集时,可以跳过当前的结果集,跳到下一个结果集:

Cursor.nextset()

如果当前结果集还有数据行未被读取,那么这些剩余的数据行会被丢弃。

四,执行存储过程

Cursor对象有函数callproc,用于执行存储过程:

Cursor.callproc(sp_name, paras)

第一个参数是存储过程的名称,第二个参数是一个元组类型,

五,pymssql模块的基本操作

 1,pymssql的基本操作

from os import getenv
import pymssql server = getenv("PYMSSQL_TEST_SERVER")
user = getenv("PYMSSQL_TEST_USERNAME")
password = getenv("PYMSSQL_TEST_PASSWORD") conn = pymssql.connect(server, user, password, "tempdb")
cursor = conn.cursor(as_dict=False)
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.')])
# you must call commit() to persist your data if you don't set autocommit to True
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() conn.close()

2,以字典集返回数据行

conn = pymssql.connect(server, user, password, "tempdb")
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()

3,使用with语句

with是上下文管理器,可以自动关闭上下文。

使用with语句来创建连接对象和Cursor对象,那么就不需要显式的关闭连接和Cursor对象:

with pymssql.connect(server, user, password, "tempdb") 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']))

六,附上代码库

附上代码,以飨读者。

import pymssql
from sqlalchemy import create_engine
import pandas as pd
from sqlalchemy.sql import text as sql_text class DBHelper:
def __init__(self):
self.name='DB Helper'
self.db_host = r'sql server'
self.db_name = 'db name'
self.db_user = r'sa'
self.db_password = r'pwd' ######################################################
## data connection ##
###################################################### def get_engine(self):
str_format = 'mssql+pymssql://{0}:{1}@{2}/{3}?charset=utf8'
connection_str = str_format.format(self.db_user,self.db_password,self.db_host,self.db_name)
engine = create_engine(connection_str,echo=False)
return engine def get_pymssql_conn(self):
conn = pymssql.connect(self.db_host, self.db_user, self.db_password, self.db_name)
return conn ######################################################
## common SQL APIs ##
###################################################### def write_data(self,df,destination,if_exists='append',schema='dbo'):
engine = self.get_engine()
df.to_sql(destination, con=engine, if_exists=if_exists,index = False, schema=schema
, method='multi', chunksize=1000) def read_data(self,sql):
engine = self.get_engine()
df = pd.read_sql(sql, con=engine)
return df def exec_sql(self,sql):
engine = self.get_engine()
con = engine.connect()
with con.begin() as tran:
con.execute(sql_text(sql).execution_options(autocommit=True)) def exec_sp(self,sp_name,*paras):
with pymssql.connect(self.db_host, self.db_user, self.db_password, database=self.db_name) as conn:
with conn.cursor(as_dict=False) as cursor:
try:
cursor.callproc(sp_name, paras)
conn.commit()
except Exception as e:
print(e) def exec_sp_result(self,sp_name,*paras):
with pymssql.connect(self.db_host, self.db_user, self.db_password, database=self.db_name) as conn:
with conn.cursor(as_dict=True) as cursor:
try:
cursor.callproc(sp_name, paras)
cursor.nextset()
result=cursor.fetchall() conn.commit()
df=pd.DataFrame.from_records(result) return df
except Exception as e:
print(e)

参考文档:

pymssql introduction

pymssql 介绍的更多相关文章

  1. win 下python2.7 pymssql连接ms sqlserver 2000

    python DB-API 连接mysql 要用到库pymssql 下载请到https://pypi.python.org/pypi/pymssql/2.0.1我这里下载的是ms windows in ...

  2. centos下python的pymssql模块安装及简单使用

    1.安装pymssq模块 1-1.环境准备: 1-1-1.unixODBC安装 yum install unixODBC unixODBC-devel -y 1-1-2.freetds安装 下载 fr ...

  3. python:利用pymssql模块操作SQL server数据库

    python默认的数据库是 SQLlite,不过它对MySql以及SQL server的支持也可以.这篇博客,介绍下如何在Windows下安装pymssql库并进行连接使用... 环境:Windows ...

  4. Python用MySQLdb, pymssql 模块通过sshtunnel连接远程数据库

    转载自 https://www.cnblogs.com/luyingfeng/p/6386093.html 安全起见,数据库的访问多半是要做限制的,所以就有一个直接的问题是,往往多数时候,在别的机器上 ...

  5. pymssql连接Azure SQL Database

    使用pymssql访问Azure SQL Database时遇到"DB-Lib error message 20002, severity 9:\nAdaptive Server conne ...

  6. pymssql默认关闭自动模式开启事务行为浅析

    使用Python采集SQL Server数据库服务器磁盘信息时,遇到了一个错误"CONFIG statement cannot be used inside a user transacti ...

  7. CSS3 background-image背景图片相关介绍

    这里将会介绍如何通过background-image设置背景图片,以及背景图片的平铺.拉伸.偏移.设置大小等操作. 1. 背景图片样式分类 CSS中设置元素背景图片及其背景图片样式的属性主要以下几个: ...

  8. MySQL高级知识- MySQL的架构介绍

    [TOC] 1.MySQL 简介 概述 MySQL是一个关系型数据库管理系统,由瑞典MySQL AB公司开发,目前属于Oracle公司. MySQL是一种关联数据库管理系统,将数据保存在不同的表中,而 ...

  9. Windows Server 2012 NIC Teaming介绍及注意事项

    Windows Server 2012 NIC Teaming介绍及注意事项 转载自:http://www.it165.net/os/html/201303/4799.html Windows Ser ...

随机推荐

  1. day23:单继承&多继承&菱形继承&__init__魔术方法

    1.单继承 1.1 关于继承的一些基本概念 1.2 子类可以调用父类的公有成员 1.3 子类无法调用父类的私有成员 1.4 子类可以改写父类的方法 2.多继承 2.1 多继承的基本语法 2.2 sup ...

  2. 一文说通C#中的异步编程补遗

    前文写了关于C#中的异步编程.后台有无数人在讨论,很多人把异步和多线程混了. 文章在这儿:一文说通C#中的异步编程 所以,本文从体系的角度,再写一下这个异步编程.   一.C#中的异步编程演变 1. ...

  3. CSS可见格式化模型

    1.盒模型 1.1 盒子大小 盒模型描述了元素如何显示,以及如何相互作用.相互影响. 页面中的所有元素都被看作一个矩形盒子,这个盒子包含元素的内容.内边距.边框和外边距. 给元素应用的背景会作用于元素 ...

  4. 曲线生成与求交—B样条曲线

    B样条曲线生成 Bezier曲线缺点:改变任一控制点的位置,将影响整条曲线的形状. B样条曲线是对Bezier曲线的改进,可进行局部控制,生成的曲线与控制多边形的外形更接近,将Bezier曲线作为一特 ...

  5. Vouch-proxy 实现 Zabbix4.4 对接 SSO

    Vouch-proxy 实现 Zabbix 对接 SSO Zabbix 自身不支持 SSO 对接,我使用 Nginx 代理 Zabbix,将请求转发至 Vouch-proxy,由 Vouch-prox ...

  6. 尝试Access数据库注入实验

    靶场环境:https://www.mozhe.cn/bug/detail/82 首先http://219.153.49.228:49543/new_list.asp?id=1 order by 4 到 ...

  7. 02树莓派4B—C语言编程——PWM

    01树莓派直接输出PWM波 —— 硬件PWM程序  (推荐使用) #include <stdio.h> #include <wiringPi.h> #include <s ...

  8. ssh断连后,保持Linux后台程序连接

    #### ssh断连后,如何保持Linux后台程序继续运行?ssh断连后,要想运行在Linux服务器中的程序继续运行,就要用到screen技术.- ##### 新建`session` ```shell ...

  9. 轻量级Java EE企业应用实战:Struts2+Spring5+Hibernate5/JPA2

    轻量级Java EE企业应用实战(第5版)——Struts 2+Spring 5+Hibernate 5/JPA 2整合开发是<轻量级Java EE企业应用实战>的第5版,这一版保持了前几 ...

  10. AS 新电脑clone项目报错:Clone failed: Authentication failed for 'https://gitee.com/XXX/Demo.git/'

    在新的电脑上安装Android Studio,并且使用git clone 项目,报以下错误: Clone failed: Authentication failed for 'https://gite ...