Python 蟒蛇:MYSQLdb。如何在大表中不执行select * 的情况下获取列名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23786674/
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
python: MYSQLdb. how to get columns name without executing select * in a big table?
提问by MacSanhe
I want to get the column names of a table, but there a over million data in it. So I cannot use:
我想获取表的列名,但其中有超过一百万的数据。所以我不能使用:
cursor.execute("SELECT * FROM table_name")
print cursor.description
And in sqlite3, I do it this way
而在 sqlite3 中,我是这样做的
crs.execute("PRAGMA table_info(%s)" %(tablename[0]))
for info in crs:
print info
But this is not working in python mysqldb. Any one know how to do that?
但这在 python mysqldb 中不起作用。有谁知道怎么做?
采纳答案by alecxe
You can use SHOW columns
:
您可以使用SHOW columns
:
cursor.execute("SHOW columns FROM table_name")
print [column[0] for column in cursor.fetchall()]
FYI, this is essentially the same as using desc
:
仅供参考,这与使用基本相同desc
:
cursor.execute("desc table_name")
print [column[0] for column in cursor.fetchall()]
回答by ebarr
The correct way to do this would be to use "SHOW columns FROM table_name"
however, you could also simply add a LIMIT
to your existing query:
执行此操作的正确方法是使用,"SHOW columns FROM table_name"
但您也可以简单地将 a 添加LIMIT
到现有查询中:
cursor.execute("SELECT * FROM table_name LIMIT 0")
print cursor.description
回答by Missing Semicolon
Try
尝试
cursor.execute("SELECT * FROM table_name LIMIT 1")
or
或者
cursor.execute("SELECT * FROM table_name WHERE 1=0")
Both prevent massive amounts of data being rattled. The second one is perhaps more elegant. I've just checked, and even this works:
两者都可以防止大量数据混乱。第二个可能更优雅。我刚刚检查过,即使这样也有效:
>>>cursor.execute("SELECT LEFT(long_text,5) as short_text FROM table_name WHERE 1=0")
>>>print cursor.description
(('short_text', 253, 0, 5, 5, 31, 0),)
回答by YH Wu
cursor.execute("SELECT * FROM table_name LIMIT 0")
cursor.column_names
Use the following to find other information
使用以下内容查找其他信息
[v for v in dir(cursor) if v.find("_")]