1

I'm very new to Python. How can we drop and create the database in Python?

I'm using MySql and Windows server 2003.

Note: I have all the queries, Drop, create and insert records everything in a input.sql

So I want to import input.sql.

Can anyone help me?

1 Answer 1

2

If you have access to the mysql client, then this is trivial:

mysql -u username -p database < input.sql

This will prompt you for a password; if you want to supply the password inline:

mysql -u username -ppassword database < input.sql

Run any of the above from Python using the subprocess module.

The not-so-easy way would be to read each line of the file - do some logic to grab entire SQL statements - and then execute it against the database "manually", but this would just replicate what the mysql command is doing:

import MySQLdb
db = MySQLdb.connect(username="foo",passwd="secret",db="mydb")
c = db.cursor()

with open('input.sql') as f:
   for line in f:
      proper_sql = some_magic_function(line)
      c.execute(proper_sql)
      db.commit()
Sign up to request clarification or add additional context in comments.

1 Comment

Plus, the not-so-easy way would not work the same, as the default mysql client will detect open brackets etc. and thus allow statements spanning over multiple lines.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.