4

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?

Community
  • 1
  • 1
kyrenia
  • 5,431
  • 9
  • 63
  • 93
  • 1
    Do you have a MySQL server installed on localhost? – msturdy Nov 17 '15 at 22:39
  • No - would i be right in assuming therefore that if i were to install `MySQL Community Server` from mysql.com that the above code should work to create the database? – kyrenia Nov 17 '15 at 22:42
  • yes you need to install mysql server. Your code won't create the database, it will connect to the server and attempt to connect to a database called `jonhydb` already created therein. You might want to consider installing the MySQL Workbench too to help you set up your database and tables – msturdy Nov 17 '15 at 22:44
  • so presumably, i will need to first create a database from within the MySQL server with that name, and then connect to it from Python? – kyrenia Nov 17 '15 at 22:45
  • while you can create it from Python, it's not common practice, as each time you run the script it will attempt to create the db. Somewhere you'll need to run the [create database](https://dev.mysql.com/doc/refman/5.5/en/create-database.html) command, either in MySQL (command line or Workbench), or via Python – msturdy Nov 17 '15 at 22:50

2 Answers2

10

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

msturdy
  • 10,479
  • 11
  • 41
  • 52
0

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()
Codemaker2015
  • 12,190
  • 6
  • 97
  • 81