Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : How to create mysql databases with PyMySQL?

Tags:

python

mysql

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?

like image 311
zwl1619 Avatar asked Sep 05 '17 12:09

zwl1619


People also ask

What is the difference between PyMySQL and MySQL?

PyMySQL and MySQLdb provide the same functionality - they are both database connectors. The difference is in the implementation where MySQLdb is a C extension and PyMySQL is pure Python. There are a few reasons to try PyMySQL: it might be easier to get running on some systems.


1 Answers

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 (...)')
like image 181
Thomas Munk Avatar answered Nov 08 '22 01:11

Thomas Munk