在 pandas.read_sql 中列出 sql 表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33020371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:00:25  来源:igfitidea点击:

List sql tables in pandas.read_sql

pythonsqlsql-serverpandas

提问by tnknepp

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

我想打开一个 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)

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.

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

回答by Biazi Bayer

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

回答by measureallthethings

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

这个答案可能会有所帮助:如何使用 TSQL 获取数据库中所有表的列表?

Trying changing your SQL string to:

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

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