kyrenia
kyrenia

Reputation: 5565

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?

Upvotes: 4

Views: 10100

Answers (2)

Codemaker2015
Codemaker2015

Reputation: 1

install mysql connector using pip,

sudo pip install mysql-connector-python

Sample code to create database gtec and table student,

import mysql.connector    
cnx = mysql.connector.connect(user='root', password='1234',
                              host='localhost',
                              database='gtec')

try:
   cursor = cnx.cursor()
   cursor.execute("select * from student")
   result = cursor.fetchall()
   print result
finally:
    cnx.close()

Upvotes: 0

msturdy
msturdy

Reputation: 10794

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

Upvotes: 10

Related Questions