kjfhgds 发表于 2016-7-19 10:27:27

python 操作SQL SERVER数据库

首先安装pymssql模块

1
2
3
4
5
6
7
8
9
10
pip install pymssql

Collecting pymssql
Downloading pymssql-2.1.3-cp35-cp35m-win_amd64.whl (367kB)
    100% |████████████████████████████████| 368kB 39kB/s
Installing collected packages: pymssql
Found existing installation: pymssql 2.1.2
    Uninstalling pymssql-2.1.2:
      Successfully uninstalled pymssql-2.1.2
Successfully installed pymssql-2.1.3





事例代码:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#!/usr/bin/env python
# encoding: utf-8

"""
@version: ??
@author: phpergao
@license: Apache Licence
@file: mssql.py
@time: 2016/7/18 10:18
"""
import pymssql


class MSSQL:
    """
    对pymssql的简单封装
    pymssql库,该库到这里下载:http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql
    使用该库时,需要在Sql Server Configuration Manager里面将TCP/IP协议开启

    用法:

    """

    def __init__(self,host,user,pwd,db):
      self.host = host
      self.user = user
      self.pwd = pwd
      self.db = db

    def __GetConnect(self):
      """
      得到连接信息
      返回: conn.cursor()
      """
      if not self.db:
            raise(NameError,"没有设置数据库信息")
      self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8")
      cur = self.conn.cursor()
      if not cur:
            raise(NameError,"连接数据库失败")
      else:
            return cur

    def ExecQuery(self,sql):
      """
      执行查询语句
      返回的是一个包含tuple的list,list的元素是记录行,tuple的元素是每行记录的字段

      调用示例:
                ms = MSSQL(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics")
                resList = ms.ExecQuery("SELECT id,NickName FROM WeiBoUser")
                for (id,NickName) in resList:
                  print str(id),NickName
      """
      cur = self.__GetConnect()
      cur.execute(sql)
      resList = cur.fetchall()

      #查询完毕后必须关闭连接
      self.conn.close()
      return resList

    def ExecNonQuery(self,sql):
      """
      执行非查询语句

      调用示例:
            cur = self.__GetConnect()
            cur.execute(sql)
            self.conn.commit()
            self.conn.close()
      """
      cur = self.__GetConnect()
      cur.execute(sql)
      self.conn.commit()
      self.conn.close()

def main():
## ms = MSSQL(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics")
## #返回的是一个包含tuple的list,list的元素是记录行,tuple的元素是每行记录的字段
## ms.ExecNonQuery("insert into WeiBoUser values('2','3')")

    ms = MSSQL(host="192.168.1.1",user="sa",pwd="123456789",db="stddata")
    resList = ms.ExecQuery("SELECT * FROM STD_Store_Data")
    for i in resList:
      print (i)

if __name__ == '__main__':
    main()



页: [1]
查看完整版本: python 操作SQL SERVER数据库