Home >Backend Development >Python Tutorial >Use python to export mysql query data to a file

Use python to export mysql query data to a file

巴扎黑
巴扎黑Original
2016-12-08 10:40:551635browse

In python:

1. Connection:

Python code

import mysql.connector  
cnx = mysql.connector.connect(user='scott', password='tiger',  
                              host='127.0.0.1',  
                              database='employees')  
cnx.close()

2. Query:

Python code

import datetime  
import mysql.connector  
cnx = mysql.connector.connect(user='scott', database='employees')  
cursor = cnx.cursor()  
query = ("SELECT first_name, last_name, hire_date FROM employees "  
         "WHERE hire_date BETWEEN %s AND %s")  
hire_start = datetime.date(1999, 1, 1)  
hire_end = datetime.date(1999, 12, 31)  
cursor.execute(query, (hire_start, hire_end))  
for (first_name, last_name, hire_date) in cursor:  
  print("{}, {} was hired on {:%d %b %Y}".format(  
    last_name, first_name, hire_date))  
cursor.close()  
cnx.close()

3. Output to file (use current date as file name)

Python code

import time  
filename = 'page_list_'+str(time.strftime("%Y%m%d"))+'.txt'  
output = open(filename,'w')  
output.write(str(page_title).lstrip('(b\'').rstrip('\',)')+"\n")  
output.close()

here page_title is the field name retrieved from the database above. Because the output is all in the format of (b'pagename'), some processing was done to delete redundant characters.

In this way, the retrieved content can be directly saved to a file named with date.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn