Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List sql tables in pandas.read_sql

I would like to open an SQL 2005 database (file has extension of .mdf), and I have been trying this as such:

import pandas as pd
import pyodbc

server = 'server_name'
db = 'database_name'

conn = pyodbc.connect('DRIVER={SQL Server};SERVER=' + server + ';DATABASE=' + db + ';Trusted_Connection=yes')

sql = """

SELECT * FROM table_name

"""
df = pd.read_sql(sql, conn)

Is there a way to query the database and list all tables using Pandas or pyodbc? I have virtually NO experience in databases, so any help will be great.

like image 920
tnknepp Avatar asked Oct 08 '15 15:10

tnknepp


3 Answers

This answer might be helpful: How do I get list of all tables in a database using TSQL?

Trying changing your SQL string to:

sql = """
SELECT * FROM information_schema.tables
"""
like image 155
measureallthethings Avatar answered Nov 01 '22 14:11

measureallthethings


import pyodbc as db

import pandas as pd

conn = db.connect("DRIVER={SQL Server}; SERVER=YourServerName; PORT=1433; DATABASE=YourDB; UID=User; PWD=Password;")

cursor = conn.cursor()

cursor.execute('''select * from sys.databases''')

df=pd.DataFrame(cursor.fetchall())
like image 3
Citizen Avatar answered Nov 01 '22 15:11

Citizen


With sqllite3 and pandas you can do it by

import sqlite3 
import pandas as pd 
  
# create a connection 
con = sqlite3.connect('database.db') 
data = pd.read_sql_query('SELECT name from sqlite_master where type= "table";', con) 
  
# show first 5 table names
data.head()
like image 1
Hunaidkhan Avatar answered Nov 01 '22 15:11

Hunaidkhan