前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python利用pymssql连接SQL

python利用pymssql连接SQL

作者头像
py3study
发布2020-01-08 10:44:32
1.9K0
发布2020-01-08 10:44:32
举报
文章被收录于专栏:python3python3

首先需要安装pymssql模块

配置下freetds

#cat /usr/local/freetds/etc/freetds.conf

代码语言:javascript
复制
#   $Id: freetds.conf,v 1.12 2007/12/25 06:02:36 jklowden Exp $
#
# This file is installed by FreeTDS if no file by the same 
# name is found in the installation directory.  
#
# For information about the layout of this file and its settings, 
# see the freetds.conf manpage "man freetds.conf".  

# Global settings are overridden by those in a database
# server specific section
[global]
       # TDS protocol version
;tds version = 4.2

# Whether to write a TDSDUMP file for diagnostic purposes
# (setting this to /tmp is insecure on a multi-user system)
;dump file = /tmp/freetds.log
;debug flags = 0xffff
# Command and connection timeouts
;timeout = 10

;connect timeout = 10

# If you get out-of-memory errors, it may mean that your client
# is trying to allocate a huge buffer for a TEXT field.  
# Try setting 'text size' to a more reasonable limit 
text size = 64512

# A typical Sybase server#newadd
[test_db]
      host = 127.0.0.1
      port = 1433
      tds version = 8.0
      client charset = GBK

连接SQL服务器的代码

代码语言:javascript
复制
import sys
import pymssql
class Mssql:
    def __init__(self, config):
        self.cf = config
    def __Connect(self):
        try:
            self.conn = pymssql.connect(host=self.cf['host'],user=self.cf['user'],password=self.cf['pwd'],database=self.cf['db'])
            cur = self.conn.cursor()
        except Exception, err:
            print "Error decoding config file: %s" % str(err)
            sys.exit(1)
        return cu
                                                                                                                                                                                                                                                                                                                                                                                               
    def select(self, sql):
        try:
            cur = self.__Connect()
            cur.execute(sql)
            rows = cur.fetchall()
            cur.close()
            self.conn.close()
            return rows
        except Exception, err:
            print "Error decoding config file: %s" % str(err)
            sys.exit(1)
    def insert(self, sql):
        try:
            cur = self.__Connect()
            cur.execute(sql)
            cur.close()
            self.conn.commit()
            self.conn.close()
        except Exception, err:
            print "Error decoding config file: %s" % str(err)
            sys.exit(1)
def main():
    config = {'host':'test_db','user':'test','pwd':'123456','db':'Testdb'}
    mssql = Mssql(config)
                                                                                                                                                                                                                                                                                                                                                                                               
    #select sql
    sql = "select * from test_table"
    rows = mssql.select(sql)
    #insert sql
    sql = "insert into test_table values('1','2','3')"
    mssql.insert(sql)
if __name__ == "__main__":
    main()

注:host里test_db是调用freetds配置里的,可以直接写ip

下面是pymssql里参数使用说明,如下:

1. pymssqlCnx类(用于连接Mssql数据库)

pymssql.connect()来初始化连接类,它允许如下的参数。

代码语言:javascript
复制
dsn:连接字符串,主要用于与之前版本的pymssql兼容

user:用户名

password:密码

trusted:布尔值,指定是否使用windows身份认证登陆

host :主机名

database:数据库

timeout:查询超时

login_timeout:登陆超时

charset:数据库的字符集

as_dict:布尔值,指定返回值是字典还是元组

max_conn:最大连接数

2. Method

代码语言:javascript
复制
autocommit(status)
布尔值,指示是否自动提交事务,默认的状态是关闭的,如果打开,你必须调用commit()方法来提交事务。



close()
关闭连接



cursor()
返回游标对象,用于查询和返回数据
commit()
提交事务。



rollback()
回滚事务

pymssqlCursor类
用于从数据库查询和返回数据

rowcount
返回最后操作影响的行数。



connection
返回创建游标的连接对象



lastrowid
返回插入的最后一行

rownumbe
返回当前数据集中的游标(通过索引)

3. 游标方法

代码语言:javascript
复制
close()
关闭游标
execute(operation)
执行操作
execute(operation, params)
执行操作,可以提供参数进行相应操作
executemany(operation, params_seq)
执行操作,Params_seq为元组
fetchone()
在结果中读取下一行

fetchmany(size=None)
在结果中读取指定数目的行

fetchall()
读取所有行

nextset()
游标跳转到下一个数据集
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档