Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a MySQL database in python

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?

like image 733
kyrenia Avatar asked Dec 24 '22 12:12

kyrenia


1 Answers

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

like image 197
msturdy Avatar answered Jan 01 '23 18:01

msturdy