List names of all available MS SQL databases on server using python
Asked Answered
M

4

6

Trying to list the names of the databases on a remote MS SQL server using Python (Just like the Object Explorer in MS SQL Server Management Studio).

Current solution: The required query is SELECT name FROM sys.databases;. So current solution is using SQLAlchemy and Pandas, which works fine as below.

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)

output:

                  name
0               master
1               tempdb
2                model
3                 msdb

Question: How to list the names of the databases on the server using SQLAlchemy's inspect(engine) similar to listing table names under a database? Or any simpler way without importing Pandas?

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']
Mizzen answered 29/12, 2015 at 1:36 Comment(6)
They should exist in inspector.get_table_names(); have you tried print(inspector.get_table_names())?Highroad
Thanks! Already tried. This does return table names under a DB name, but not the DB names in the server.Mizzen
D'oh! I clearly have my brain shut off during this holiday week, and misread the question entirely. I'm guessing in SQL Server get_schema_names() wouldn't work, since you'd just get a list of dbos? It is worth a shot; I don't have my SQL Server rig handy, or I'd do some testing (off of work this week).Highroad
get_schema_names() returns identical results for two different servers. So guessing that it shows the default building blocks of the servers, not the in-house DB names that I want. Edited the question with more infoMizzen
I think you meant get_schema_names instead of get_table_names in your code block?Highroad
No it is right. Did not show get_schema_names() output. Now now added them as well. But none of get_schema_names and get_table_names yield required info.Mizzen
A
5

If all you really want to do is avoid importing pandas then the following works fine for me:

from sqlalchemy import create_engine
engine = create_engine('mssql+pymssql://sa:saPassword@localhost:52865/myDb')
with engine.connect() as conn:
    rows = conn.exec_driver_sql("select name FROM sys.databases;").scalars().all()
print(rows)
# ['master', 'tempdb', 'model', 'msdb', 'test']
Aposiopesis answered 31/12, 2015 at 0:40 Comment(1)
Thanks! engine.connect().execute(...) works, even when port and DB name are not rovided in create_engine()!Mizzen
S
2

It is also possible to obtain tables from a specific scheme with execute the single query with the driver below: 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])

output:

my_table_name_1
my_table_name_2
my_table_name_3
...
my_table_name_x
Songful answered 28/12, 2020 at 10:2 Comment(0)
F
1

I believe the following snippet will list the names of the available databases on whatever server you choose to connect to. This will return a JSON object that will be displayed in your browser. This question is a bit old, but I hope this helps anyone curious who stops by.

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')
Fortunio answered 20/4, 2017 at 0:7 Comment(0)
M
0

here is another solution which fetch row by row:

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()
Macnair answered 14/10, 2016 at 4:18 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.