python: MYSQLdb. how to get columns name without e

2020-02-26 08:06发布

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

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?

4条回答
贪生不怕死
2楼-- · 2020-02-26 08:32

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),)
查看更多
一夜七次
3楼-- · 2020-02-26 08:35

You can use 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:

cursor.execute("desc table_name")
print [column[0] for column in cursor.fetchall()]
查看更多
时光不老,我们不散
4楼-- · 2020-02-26 08:39

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:

cursor.execute("SELECT * FROM table_name LIMIT 0")
print cursor.description
查看更多
Rolldiameter
5楼-- · 2020-02-26 08:45
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("_")]
查看更多
登录 后发表回答