Python connects to the database there are several methods, but for the data retrieved from the database format is somewhat different, back to the tuple format of data processing is more troublesome, next introduced a back to the list format of the connection method, list format data processing and use is more convenient.
#!/usr/bin/python
#-*-Coding:utf-8-*-
#!/usr/bin/env python
Import MySQLdb
From commands import Getstatusoutput, getoutput
Import Sys
Reload (SYS)
Sys.setdefaultencoding (' Utf-8 ')
cmd = "Mysql-h host address Connect-u user name-p password-e" Use database name; Select XXX "'"
(result,info) = Getstatusoutput (cmd) #info为数据值, result is a performance
info = Info.splitlines ()
File = Open ("Name.txt", ' W ') #打开txt文件
File.write ("xxx,xxx,xxx") #往txt写入第一行数据
#往txt文件一行一行的写入查出的数据
File.write ("\ n") #换行
For I in range (len (info)):
If I! = 0 and I! = 1: #由于密码写在文件里会报出一行密码告警提示
File.write (Info[i]) #并且第一行查回的数据为数据标题字段名, so useless
File.write ("\ n") #只留下有效数据写入文件
File.close () #关闭txt
Python script--a way to connect to a MySQL database (retrieve data as list non-tuple format) and write data to TXT