Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: MYSQLdb. how to get columns name without executing select * in a big table?

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?

like image 910
MacSanhe Avatar asked May 21 '14 14:05

MacSanhe


1 Answers

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()]
like image 56
alecxe Avatar answered Oct 23 '22 06:10

alecxe