博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
pymssql
阅读量:5750 次
发布时间:2019-06-18

本文共 1522 字,大约阅读时间需要 5 分钟。

用与连接sql server数据库的python接口

import pymssql

1.配置信息

conf={

        "host": "118.190.41.846:9099",

        "user": "sa",

        "password": "123",

        "database": "water"} 

如果是连接本地的数据库,host可以写为本机的数据库名例‘DESKTOP-K06BHO8’

 

2.连接数据库

conn=pymssql.connect(**conf)

cur=conn.cursor()   #默认返回元组,使用as_dict='True'设置为返回字典形式的列表

#用with功能,避免忘记关闭连接与游标

# with pymssql.connect(**config["test2"]) as conn:

#     with conn.cursor(as_dict=True) as cursor:

#         cursor.execute('SELECT top 10 * FROM tbluserinfo WHERE userid=%s', 'John Doe')

#         #通过迭代方式获取查询结果

#         for row in cursor:

#             print("ID=%d, Name=%s" % (row['id'], row['name']))

# conn.commit()

3.执行sql语句

sql='select * from readdata'

cur.execute(sql)

execute('insert into test3(username,address,type) values(%s,%s,%d)',('wingwed','3 street 4 block',3))

该方法有两个参数,可在sql语句中使用入参,字符型用%s,数字型用%d,

第二个参数必须是元组或dict类型,列表类型会报错。

也可一次写入多条记录

executemany("INSERT INTO persons VALUES (%d, %s, %s)",

    [(1, 'John Smith', 'John Doe'),

    (2, 'Jane Doe', 'Joe Dog'),

    (3, 'Mike T.', 'Sarah H.')])

4.获取执行结果

data=cur.fetchall()#获取所有结果,返回每条记录元组组成的列表

#data=cur.fetchone() 获取一条结果,返回单个元组,当查询结果记录数为0时,不会报错,会返回None.

#通过迭代方式获取查询结果

#         for row in cur:

#             print("ID=%d, Name=%s" % (row['id'], row['name']))

 

#5.调用存储过程

 # 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']))

 

转载于:https://www.cnblogs.com/Ting-light/p/9547265.html

你可能感兴趣的文章
ubutun 中 Eclipse中 快捷键 Alt + / 不能使用的问题
查看>>
Redis学习手册(内存优化)
查看>>
浅尝TensorFlow on Kubernetes
查看>>
wnmp-3.1.0安装cakephp启动失败处理
查看>>
springboot系列十 Spring-Data-Redis
查看>>
Confluence 6 注册外部小工具
查看>>
excel进行矩阵计算
查看>>
基于Android平台的动态生成控件和动态改变控件位置的方法
查看>>
Java集合(二) Map 架构
查看>>
linux 死机分析
查看>>
BOM
查看>>
curl/wget 测试http请求的响应头信息
查看>>
LeetCode:Nim Game - 尼姆博弈
查看>>
Python装饰器高级版—Python类内定义装饰器并传递self参数
查看>>
Linux解压unzip用法
查看>>
我的友情链接
查看>>
Camara 自定义预览效果
查看>>
SAP: Unit PC is not created in language EN
查看>>
SQL查找出某一列中存在重复的数据
查看>>
Windows Server 2012 系统群集
查看>>