I am looking to a create a MySQL database from within Python. I can find instructions for how to connect to an existing database, but not how to initialize a new one.
For example, when i run the line
import MySQLdb
db = MySQLdb.connect(host="localhost", user="john", passwd="megajonhy", db="jonhydb") (presumably because connecting will not create a database if it doesn't already exist, as i had hoped)
Which is the first line of instructions on How do I connect to a MySQL Database in Python? I get the error _mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (10061)")
How do i go about initializing a new MySQL database to work with?
Creating a database in Python.
import MySQLdb
db = MySQLdb.connect(host="localhost", user="user", passwd="password")
c = db.cursor()
c.execute('create database if not exists pythontest')
db.close()
Using the CREATE DATABASE MySQL statement.
This is not common practice as it will attempt to create that database each time you run the script.
Note - you can then use db.select_db('pythontest')
to select that table and c.execute('create table statement')
to create a table
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With