Python与数据库[1] -> 数据库接口/DB-API[2] -> SQL Server 适配器

SQL_Server适配器 / SQL_Server Adapter


 

1 环境配置 / Environment Configuration

安装SQL_Server的Python适配器包

pip install pymssql  

Note: 此处采用远程数据库服务器,因此未安装本地SQL_Server

 

2 SQL_Server实例 / SQL_Server Examples

 

由于远程数据库账号仅具有读取权限,因此此处示例基本以读取为主。

查看数据库 / Show Database

利用适配器的基本函数登录远程数据库服务器,并查看服务器中数据库名称,表名称等信息。

 1 import pymssql as ms
 2 def execute(cur, sql, *args):
 3     cur.execute(sql, *args)
 4     re = cur.fetchall()
 5     return re
 6 
 7 def show():
 8     cnx = ms.connect(host='host', user='user', password='password', database='db', charset='UTF-8')
 9     
10     cur = cnx.cursor()
11     
12     print('{:-^30}'.format('DATABASES'))
13     # Show the database in sys
14     re = execute(cur, "SELECT * FROM sys.databases")
15     
16     # Show custom databases
17     # re = execute(cur, "SELECT * FROM sys.databases WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb')")
18     for db in re:
19         try:
20             # Select databases
21             cur.execute("USE %s" % db[0])
22         except:
23             continue
24         # Show tables
25         re = execute(cur, "SELECT * FROM information_schema.TABLES")
26     
27         for i in re:
28             print(i)
29     
30     cur.execute('USE ITP')
31     print('{:-^30}'.format('TABLES'))
32     re = execute(cur, "SELECT * FROM information_schema.TABLES")
33     for tb in re:
34         print('\n{:-^30}'.format('TABLE CONTENTS'))
35         print(tb)
36         print('{:-^30}'.format('%s' % tb[2]))
37         re = execute(cur, "SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME='%s'" % tb[2])
38         for cl in re:
39             print(cl)
40 
41 def foo(gen):
42     [print(x, end='\n\n') for x in gen]
43 
44 if __name__=='__main__':
45     show()

第 2-4 行,首先定义一个执行函数,利用传入的游标执行SQL语句

第 7-39 行,定义一个显示函数,其中sys.databases中存放了所有数据库的名称信息,show函数会将所有database的信息显示出来,并查看db表的信息

此处的数据库信息均已隐藏,可以看出,无论是SQL_Server还是MySQL,利用适配器进行操作时,基本原理都是相同的,只有部分SQL语句不同。

 

相关阅读


1. 使用 Python 建立 MySQL 适配器

 2. DB-API 通用标准

posted @ 2018-01-02 19:57  StackLike  阅读(436)  评论(0编辑  收藏  举报