John
John

Reputation: 341

Python MYSQL to Text File - Headings Required

I have some code to query a MYSQL database and send the output to a text file. The code below prints out the first 7 columns of data and sends it to a text file called Test My question is, how do i also obtain the column HEADINGS from the database as well to display in the text file? I am using Python 2.7 with a MYSQL database.

import MySQLdb
import sys

connection = MySQLdb.connect (host="localhost", user = "", passwd = "", db =    
"")
cursor = connection.cursor ()
cursor.execute ("select * from tablename")
data = cursor.fetchall ()
OutputFile = open("C:\Temp\Test.txt", "w")

for row in data :
   print>>OutputFile, row[0],row[1],row[2],row[3],row[4],row[5],row[6]

OutputFile.close()
cursor.close ()
connection.close ()
sys.exit()

Upvotes: 0

Views: 323

Answers (1)

KoolDev
KoolDev

Reputation: 11

The best way to get the details of the column name is by using INFORMATION_SCHEMA

SELECT `COLUMN_NAME` 
FROM `INFORMATION_SCHEMA`.`COLUMNS` 
WHERE `TABLE_SCHEMA`='yourdatabasename' 
AND `TABLE_NAME`='yourtablename';

or by using the SHOW command of mySQL

SHOW columns FROM your-table;

This command is only mySQL specific.

and then to get the data you can use the .fetchall() function to get the details.

Upvotes: 1

Related Questions