1

I have a .sql file and I want to know if we can execute it directly in python using mysql.connector python class provided my mysql community.

Usually I can execute the .sql file in mysql server in terminal using these queries,

CREATE DATABASE test;
USE test;
source data.sql;

but I want to do it in python directly. Is it possible?

1 Answer 1

5

Yes you just need to read the file then execute the string contents on the cursor... something like this

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  passwd="yourpassword"
)
with open('something.sql', 'r') as f:
    with mydb.cursor() as cursor:
        cursor.execute(f.read(), multi=True)
    mydb.commit()
Sign up to request clarification or add additional context in comments.

5 Comments

thank you :) I just have two questions, will this work when my each sql-query is multi line? Also, how can I use (or) query the database (i.e I mean how can I check tables present what is the name of database created)?
Most .sql files contain more than one sql statement. For that to work from the python connector you'll be needing to set multi=True in the execute() method call. dev.mysql.com/doc/connector-python/en/…
@O.Jones Thank you. Also how can I query the created database from the .sql file? I mean how can I use queries? For example how can I execute show tables: query? should I use mydb.execure('show tables:')
you would do the same thing cursor.execute("some sql command") but then you would need to fetch the results. results = cursor.fetchall() here results should be an iterable you can look through
With MySQL 8.0.30, I have to exclude mydb.commit(). If I include mydb.commit(), then I get the error message mysql .commit() is out of sync; you can't run this command now (this SO question). If I exclude mydb.commit(), then this approach seems to work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.