使用python列出服务器上所有可用MS SQL数据库的名称

时间:2015-12-29 01:36:32

标签: python sql-server database sqlalchemy pymssql

尝试使用Python在远程MS SQL服务器上列出数据库的名称(就像MS SQL Server Management Studio中的对象资源管理器一样)。

当前解决方案:所需的查询为SELECT name FROM sys.databases;。所以当前的解决方案是使用SQLAlchemy和Pandas,它可以正常工作,如下所示。

import pandas    
from sqlalchemy import create_engine
#database='master'
engine = create_engine('mssql+pymssql://user:password@server:port/master')
query = "select name FROM sys.databases;"
data = pandas.read_sql(query, engine)

输出:

                  name
0               master
1               tempdb
2                model
3                 msdb

问题:如何使用列出服务器上数据库的名称 SQLAlchemy的inspect(engine)类似于数据库下的列表表名?或者没有导入熊猫的任何更简单的方法?

from sqlalchemy import inspect

#trial 1: with no database name
engine = create_engine('mssql+pymssql://user:password@server:port')
#this engine not have DB name
inspector = inspect(engine)
inspector.get_table_names() #returns []
inspector.get_schema_names() #returns [u'dbo', u'guest',...,u'INFORMATION_SCHEMA']

#trial 2: with database name 'master', same result
engine = create_engine('mssql+pymssql://user:password@server:port/master')
inspector = inspect(engine)
inspector.get_table_names() #returns []
inspector.get_schema_names() #returns [u'dbo', u'guest',...,u'INFORMATION_SCHEMA']

4 个答案:

答案 0 :(得分:2)

如果您真正想做的就是避免导入大熊猫,那么以下方法对我来说没问题:

from sqlalchemy import create_engine
engine = create_engine('mssql+pymssql://sa:saPassword@localhost:52865/myDb')
conn = engine.connect()
rows = conn.execute("select name FROM sys.databases;")
for row in rows:
    print(row["name"])
制造

master
tempdb
model
msdb
myDb

答案 1 :(得分:0)

这是另一个逐行获取的解决方案:

import pymssql
connect = pymssql.connect(server, user, password, database)
cursor = connect.cursor(as_dict=True)
row = cursor.fetchone()
while row:
    for r in row.items():
        print r[0], r[1]
    row = cursor.fetchone()

答案 2 :(得分:0)

我相信以下代码段会列出您选择连接的服务器上可用数据库的名称。这将返回将在浏览器中显示的JSON对象。这个问题有点老了,但我希望这可以帮助任何好奇的人停下来。

from flask import Flask, request
from flask_restful import Resource, Api
from sqlalchemy import create_engine, inspect
from flask_jsonpify import jsonify

engine = create_engine('mssql+pymssql://user:password@server:port/master')

class AllTables(Resource):
    def get(self):
        conn = engine.connect()
        inspector = inspect(conn)
        tableList = [item for item in inspector.get_table_names()]
        result = {'data': tableList}
        return jsonify(result)

api.add_resource(AllTables, '/alltables')

app.run(port='8080')

答案 3 :(得分:0)

还可以通过使用以下驱动程序执行单个查询从特定方案中获取表:DB-API interface to Microsoft SQL Server for Python

pip install pymssql
import pymssql

# Connect to the database
conn = 
pymssql.connect(server='127.0.0.1',user='root',password='root',database='my_database')

# Create a Cursor object
cur = conn.cursor()

# Execute the query: To get the name of the tables from my_database
cur.execute("select table_name from information_schema.tables") # where table_schema = 'tableowner'
    for row in cur.fetchall():

# Read and print tables
for row in cur.fetchall():
    print(row[0])

输出:

my_table_name_1
my_table_name_2
my_table_name_3
...
my_table_name_x