Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I execute "source FileName.sql" in a python script?

I would like to execute the MySQL query source FileName.sql in a Python script on Linux.

I am able to execute other queries like SELECT * FROM table_name but this one is giving an error. I am executing this on a Linux server with a MySQL database using Python. The frontend I am using is Putty.

The Python script I have used is:

import MySQLdb
db = MySQLdb.connect("hostname","username","pswrd","dbname")
cursor = db.cursor()
cursor.execute("source FileName.sql")
db.close()

How can I execute the query source FileName.sql on the location where this file-> FileName.sql is located?

like image 747
Yamini Gera Avatar asked Dec 12 '25 13:12

Yamini Gera


1 Answers

source is not a SQL command. It's a MySQL CLI command, it only exists in the console application mysql (and wherever else implemented). All it does is to read the contents of FileName.sql and issue the SQL commands inside.

To do this in python, you can use something like

Edit: This assumes you have 1 query per line! If you have multi-line queries, you'll have to find the means to extract each query from the file.

import MySQLdb
db = MySQLdb.connect("hostname","user","pass","db")
cursor = db.cursor()
for line in open("FileName.sql"):
    cursor.execute(line)
db.close()
like image 83
Iskren Avatar answered Dec 14 '25 03:12

Iskren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!