列出pandas.read_sql中的sql表

时间:2015-10-08 15:45:20

标签: python sql sql-server pandas

我想打开一个SQL 2005数据库(文件扩展名为.mdf),我一直在尝试这样做:

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)

有没有办法查询数据库并使用Pandas或pyodbc列出所有表?我几乎没有数据库经验,所以任何帮助都会很棒。

3 个答案:

答案 0 :(得分:2)

这个答案可能会有所帮助:How do I get list of all tables in a database using TSQL?

尝试将您的SQL字符串更改为:

sql = """
SELECT * FROM information_schema.tables
"""

答案 1 :(得分:2)

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())

答案 2 :(得分:0)

使用 sqllite3 和 pandas,您可以通过

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()