5

I am using python 3.6, and I use PyMySQL to connect mysql.

I will create several databases. I want to write a Python script to do this for easily creating and removing them.

There is an example in PyMySQL docs with a piece of code like this:
PyMySQL docs :https://pymysql.readthedocs.io/en/latest/user/examples.html

connection = pymysql.connect(host='localhost',
                             user='user',
                             password='passwd',
                             db='db',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

In the code above, the database already exists.

Now there are no databases in mysql. I want to create them via python and PyMySQL. What should I do?

1 Answer 1

16

Just leave out db:

conn = pymysql.connect(host='localhost',
                       user='user',
                       password='passwd')

Then get a cursor and create a database:

conn.cursor().execute('create database dbname')

Create a table in the new database:

conn.cursor().execute('create table dbname.tablename (...)')
Sign up to request clarification or add additional context in comments.

1 Comment

You also must add this line. connection.select_db(DB_NAME)

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.