1

I have a script to send a query to MySQL and write result into the file. The issue I have is the text output looks like this:

(u'DB11A-DBD27', u'DB11A-DBD28')(u'DB62A-DBD1', u'DB62A-DBD2')(u'DB62A-DBD11', u'DB62A-DBD12')...

And I would like it to look like this:

DB11A-DBD27
DB11A-DBD28
DB62A-DBD1
DB62A-DBD2
DB62A-DBD11
DB62A-DBD12
...

Here is the code:

cnx = connectDB.cnx
query = "SELECT DB-P1,DB-P2 FROM distribution"

cur = cnx.cursor()
sql = cur.execute(query)

results = cur.fetchall()
f = open('Master.txt', 'w')
for row in results:
    row = str(row)
    print "".join(row )
    f.write(row)
f.close()

I tried strip() but kept getting type errors. Does anyone know how I can convert these tuples to list of string with each item in a new line as shown above?

Uwe
  • 41,420
  • 11
  • 90
  • 134
Damon
  • 89
  • 1
  • 9
  • What's in `results`? Can you print the output of results? Looks like you need to might need to unpack again? – Bahrom Oct 09 '17 at 20:02
  • 1
    It looks like you just want to select db-p1 union all db-p2...`SELECT DB-P1 FROM distribution u nion all SELECT DB-P2 FROM distribution` – xQbert Oct 09 '17 at 20:02

1 Answers1

1

I think you just need a union here and two selects.

Substitute union for u nion below. It won't let me save with union.

cnx = connectDB.cnx
query = "SELECT DB-P1 Z FROM distribution u nion all SELECT DB-P2 FROM distribution"

cur = cnx.cursor()
sql = cur.execute(query)

results = cur.fetchall()
f = open('Master.txt', 'w')
for row in results:
    row = str(row)
    print "".join(row )
    f.write(row)
f.close()

However if order matters we may need to know the unique key on the table so we can order appropriately.

xQbert
  • 34,733
  • 2
  • 41
  • 62
  • I added union and it did split tuples but my output file still same format. How do I get rid of u, () and save them 1 item per line? – Damon Oct 09 '17 at 22:11
  • Do you need the `print "".join(row )` couldn't the for loop just be `f.write(str(row))` now? since we only have 1 value per row? I'm by no means a python guru. SQL is my bailiwick. You can also see a similar question: https://stackoverflow.com/questions/6182964/why-is-parenthesis-in-print-voluntary-in-python-2-7 – xQbert Oct 10 '17 at 12:32
  • After further review: I'm pretty sure you're after this: https://stackoverflow.com/questions/20618640/how-to-write-to-file-without-parenthesis-in-python using the csv output; or changing the `str(row)` line to what's suggested. – xQbert Oct 10 '17 at 12:39