Python script--a way to connect to a MySQL database (retrieve data as list non-tuple format) and write data to TXT

Source: Internet
Author: User
Tags python script

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.