2013-02-13 40 views
13

Ho una tabella MySQL denominata TBLTEST con due colonne ID e qSQL. Ogni qSQL ha query SQL in esso.Inserire i dati nella tabella MySQL dallo script Python

Ho un'altra tabella FACTRESTTBL.

ci sono 10 righe della tabella di TBLTEST.

per esempio, su TBLTEST lascia prendere id = 4 e QSQL = "select id, città, stato da ABC".

Come posso inserire nel FACTRESTTBL da TBLTEST utilizzando python, può essere utilizzando il dizionario?

Thx!

+0

Si desidera eseguire la query nella colonna 'qSQL' e inserire il risultato in' FACTRESTTBL' ? Quali sono le colonne di 'FACTRESTTBL'? –

+0

Le colonne in FACTRESTTBL sono id, città – Mario

risposta

25

È possibile utilizzare MySQLdb for Python.

codice di esempio (è necessario eseguire il debug di esso come ho modo di correre qui):

#!/usr/bin/python 

import MySQLdb 

# Open database connection 
db = MySQLdb.connect("localhost","testuser","test123","TESTDB") 

# prepare a cursor object using cursor() method 
cursor = db.cursor() 

# Select qSQL with id=4. 
cursor.execute("SELECT qSQL FROM TBLTEST WHERE id = 4") 

# Fetch a single row using fetchone() method. 
results = cursor.fetchone() 

qSQL = results[0] 

cursor.execute(qSQL) 

# Fetch all the rows in a list of lists. 
qSQLresults = cursor.fetchall() 
for row in qSQLresults: 
    id = row[0] 
    city = row[1] 

    #SQL query to INSERT a record into the table FACTRESTTBL. 
    cursor.execute('''INSERT into FACTRESTTBL (id, city) 
        values (%s, %s)''', 
        (id, city)) 

    # Commit your changes in the database 
    db.commit() 

# disconnect from server 
db.close() 
+1

C'è anche https://github.com/petehunt/PyMySQL, che è pure python se questo è importante ai fini della distribuzione. – theodox

+0

La query data funziona. Poiché ci sono 10 righe in TBLTEST e soprattutto query viene eseguita se sto provando ad eseguire 1 interrogazione alla volta. Desidero eseguire più query, ad esempio: cursor.execute ("SELEZIONA qSQL DA TBLTEST DOVE id in (4, 5, 6)"), per id = 5, qSQL = "seleziona id, città, zip da DEF" per id = 6, QSQL = "select id, città, contea da ABC" Come l'hai fatto? Thx – Mario

Problemi correlati