Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execute *.sql file with python MySQLdb

Tags:

python

mysql

How can execute sql script stored in *.sql file using MySQLdb python driver. I was trying

  cursor.execute(file(PATH_TO_FILE).read())  

but this doesn't work because cursor.execute can run only one sql command at once. My sql script contains several sql statements instead. Also I was trying

 cursor.execute('source %s'%PATH_TO_FILE) 

but also with no success.

like image 713
Mykola Kharechko Avatar asked Dec 10 '10 12:12

Mykola Kharechko


People also ask

Which object is used to execute an SQL query in MySQLdb in Python?

Next, db object is used to create a cursor object, which in turn is used to execute SQL queries.


1 Answers

From python, I start a mysql process to execute the file for me:

from subprocess import Popen, PIPE process = Popen(['mysql', db, '-u', user, '-p', passwd],                 stdout=PIPE, stdin=PIPE) output = process.communicate('source ' + filename)[0] 
like image 98
jdferreira Avatar answered Oct 04 '22 14:10

jdferreira