-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtable_exporter_mysql.py
More file actions
executable file
·46 lines (35 loc) · 1.2 KB
/
table_exporter_mysql.py
File metadata and controls
executable file
·46 lines (35 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# http://mysql-python.sourceforge.net/MySQLdb.html#cursor-objects
# http://www.kitebird.com/articles/pydbapi.html
# E.g. ./table_exporter_mysql.py localhost 3306 wordpress_db root wibble_password 'select * from posts'
import csv
import sys
import MySQLdb
if __name__ == '__main__':
from optparse import OptionParser, OptionGroup
parser = OptionParser('%prog [options] HOST PORT MYSQLDB MYSQLUSERNAME MYSQLPASSWORD QUERY')
options, args = parser.parse_args()
if len(args) < 5:
import doctest
doctest.testmod()
parser.error('Not enough parameters for me to work with.')
sys.exit()
host = args[0]
port = int(args[1])
mysqldb = args[2]
username = args[3]
password = args[4]
query = args[5]
csv_writer = csv.writer(sys.stdout)
connection = MySQLdb.connect (host = host, port = port, user = username, passwd = password, db = mysqldb)
cursor = connection.cursor()
cursor.execute(query)
fields = cursor.description
csv_writer.writerow([f[0] for f in cursor.description])
row = cursor.fetchone()
while row:
csv_writer.writerow([unicode(str(r), encoding="ascii", errors='ignore') for r in row])
row = cursor.fetchone()
cursor.close()
connection.close()