1208

How do I connect to a MySQL database using a python program?

George Stocker
  • 55,025
  • 29
  • 167
  • 231
  • 47
    Most answers here focus on installing MySQLdb library, I would really suggest opting for MySQL Connector/Python provided by MySQL/Oracle, which makes the process much simpler: http://stackoverflow.com/questions/372885/how-do-i-connect-to-a-mysql-database-in-python/20959654#20959654 – Mr. Napik Jan 06 '14 at 21:32
  • 9
    The problem with using Oracle's Connector/Python is that it has subtle bugs and other integration issues. It's easy to install, but nearly impossible to get to work for all the real-world use cases I've tried it for. Hence why I always recommend MySQLdb. – Joe C. Jan 29 '15 at 17:06
  • 8
    @Mr.Napik I'm using `pymysql` because it's pure free Python according to [this comparison](https://wiki.openstack.org/wiki/PyMySQL_evaluation). – Cees Timmerman Oct 25 '16 at 18:36

27 Answers27

1274

Connecting to MYSQL with Python 2 in three steps

1 - Setting

You must install a MySQL driver before doing anything. Unlike PHP, Only the SQLite driver is installed by default with Python. The most used package to do so is MySQLdb but it's hard to install it using easy_install. Please note MySQLdb only supports Python 2.

For Windows user, you can get an exe of MySQLdb.

For Linux, this is a casual package (python-mysqldb). (You can use sudo apt-get install python-mysqldb (for debian based distros), yum install MySQL-python (for rpm-based), or dnf install python-mysql (for modern fedora distro) in command line to download.)

For Mac, you can install MySQLdb using Macport.

2 - Usage

After installing, Reboot. This is not mandatory, But it will prevent me from answering 3 or 4 other questions in this post if something goes wrong. So please reboot.

Then it is just like using any other package :

#!/usr/bin/python
import MySQLdb

db = MySQLdb.connect(host="localhost",    # your host, usually localhost
                     user="john",         # your username
                     passwd="megajonhy",  # your password
                     db="jonhydb")        # name of the data base

# you must create a Cursor object. It will let
#  you execute all the queries you need
cur = db.cursor()

# Use all the SQL you like
cur.execute("SELECT * FROM YOUR_TABLE_NAME")

# print all the first cell of all the rows
for row in cur.fetchall():
    print row[0]

db.close()

Of course, there are thousand of possibilities and options; this is a very basic example. You will have to look at the documentation. A good starting point.

3 - More advanced usage

Once you know how it works, You may want to use an ORM to avoid writing SQL manually and manipulate your tables as they were Python objects. The most famous ORM in the Python community is SQLAlchemy.

I strongly advise you to use it: your life is going to be much easier.

I recently discovered another jewel in the Python world: peewee. It's a very lite ORM, really easy and fast to setup then use. It makes my day for small projects or stand alone apps, Where using big tools like SQLAlchemy or Django is overkill :

import peewee
from peewee import *

db = MySQLDatabase('jonhydb', user='john', passwd='megajonhy')

class Book(peewee.Model):
    author = peewee.CharField()
    title = peewee.TextField()

    class Meta:
        database = db

Book.create_table()
book = Book(author="me", title='Peewee is cool')
book.save()
for book in Book.filter(author="me"):
    print book.title

This example works out of the box. Nothing other than having peewee (pip install peewee) is required.

Flimm
  • 97,949
  • 30
  • 201
  • 217
e-satis
  • 515,820
  • 103
  • 283
  • 322
  • 46
    Glad you like peewee!! I've added support for MySQL as well as some [documentation](http://charlesleifer.com/docs/peewee/peewee/uses.html#using-with-mysql) on integrating with it. Happy hacking! – coleifer Oct 31 '11 at 03:36
  • 17
    Note, as of writing this, MySQLdb does not support Python 3. The sourceforge page says "Python 3 support coming soon" but it has not been updated since 2012-10-08. For Python 3 there's [PyMySQL](https://github.com/petehunt/PyMySQL/) and [oursql](http://pythonhosted.org/oursql/index.html). – paul May 09 '13 at 03:07
  • 8
    Also note the following is required: `pip install MySQL-python` – Ben Crowhurst Sep 06 '13 at 11:51
  • To get an exe of MySQLdb for Windows x64: http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python – Franck Dernoncourt Oct 14 '13 at 22:46
  • Changing one parameter and adding "port" as another parameter doesn't seems very difficult to extrapolate from this answer. – e-satis Dec 22 '13 at 15:18
  • (host="127.0.0.1", port=3306, user="john", ... Don't forget to specify a port --**an integer**-- if you want to tap into a MySql instance running outside of the default python setup. This example works in my XAMPP and CPanel instances. – FredTheWebGuy Feb 28 '14 at 09:56
  • call `cursor.close()` after the fetchall if you are not going to use it anymore(!) – Jorge Leitao Jun 17 '14 at 06:55
  • close() is automatically called when the script exits. – e-satis Jun 17 '14 at 09:52
  • BEWARE - this module has no timezone support on connection – kommradHomer Feb 26 '15 at 09:51
  • @coleifer : your link seems to be obsolete so for new readers I'd say this is now : http://peewee.readthedocs.org/en/latest/peewee/quickstart.html#quickstart – dlewin Jan 12 '16 at 11:29
  • "This example works out of the box. Nothing other than having peewee is required" is _wrong_. To use MySQLDatabase you need to have MySQLdb or PyMySQL installed (I just got such exception message from peewee). – Ayrat Mar 30 '16 at 15:06
  • This does not work "out of the box". I found Ken Brown's answer to be simplest and want it to move up the ladder. – wetjosh Apr 12 '16 at 21:07
  • 2
    Stop using MySqlDB. Save your sanity and use pymysql it's pure python. Check the example in my response and ...you're welcome :) - http://stackoverflow.com/a/34503728/751528 – OkezieE Apr 15 '16 at 14:58
  • Your code in 2 – Usage was failing silently for me when trying to use an `INSERT` statement until I added `db.commit()` directly after the `cur.execute...` line. Without that commit command the changes were getting rolled back when the connection was closed. – Scott May 29 '16 at 10:04
  • 4
    Peewee has change the default behavior and does not use autocommit by default anymore. Even the DB driver situation has changed now. The question needs updating, but since the abuse of edits on some of my answers, I don't edit them anymore. – e-satis Jun 01 '16 at 12:57
  • 2
    Please mention that the exe file for it only supports Python versions till 2.7 as of now. – आनंद Mar 29 '17 at 18:57
  • How can I adapt this code to connect to a Google Cloud MySQL database? – matt_js Aug 22 '17 at 15:03
195

Here's one way to do it, using MySQLdb, which only supports Python 2:

#!/usr/bin/python
import MySQLdb

# Connect
db = MySQLdb.connect(host="localhost",
                     user="appuser",
                     passwd="",
                     db="onco")

cursor = db.cursor()

# Execute SQL select statement
cursor.execute("SELECT * FROM location")

# Commit your changes if writing
# In this case, we are only reading data
# db.commit()

# Get the number of rows in the resultset
numrows = cursor.rowcount

# Get and display one row at a time
for x in range(0, numrows):
    row = cursor.fetchone()
    print row[0], "-->", row[1]

# Close the connection
db.close()

Reference here

Flimm
  • 97,949
  • 30
  • 201
  • 217
George Stocker
  • 55,025
  • 29
  • 167
  • 231
  • 4
    is there a need to commit in this example as you are not modifying the database ? – sumanth232 Feb 10 '15 at 16:53
  • 3
    BEWARE - this module has no timezone support on connection – kommradHomer Feb 26 '15 at 09:50
  • It's not working on my shared hosting. Saying that `No module named MySQLdb`. How can I use mysql with python on shared hosting. Any alternative ? – Bhavesh G Apr 25 '15 at 10:05
  • @BhaveshGangani you'll need to contact your host and ask why Python libraries they support. If they support pypi, then you could always load the package when your deployment happens. – George Stocker Apr 25 '15 at 12:10
  • Don't forget to close your "db" object [db.close()], or you may experience some problems, for example, when you have a web application which must perform many connections during its life cycle. I'm a living proof of the problems that a "sleepy" connection could cause to an application, and another thing: to increase database timeouts could be a solution, but it is not a good practice to keep a timeout lasting for life. – ivanleoncz Jan 19 '17 at 17:17
  • You need to install this in order to work. yum install mysql-python (pip won't help you here). Using Centos 6. BTW. – Philippe Delteil Jan 04 '19 at 14:55
  • 1
    Interestingly even though the docs say this only works with python 2, it does seem to work with python 3 for me – lucidbrot Aug 23 '19 at 20:05
131

If you do not need MySQLdb, but would accept any library, I would very, very much recommend MySQL Connector/Python from MySQL: http://dev.mysql.com/downloads/connector/python/.

It is one package (around 110k), pure Python, so it is system independent, and dead simple to install. You just download, double-click, confirm license agreement and go. There is no need for Xcode, MacPorts, compiling, restarting …

Then you connect like:

import mysql.connector    
cnx = mysql.connector.connect(user='scott', password='tiger',
                              host='127.0.0.1',
                              database='employees')

try:
   cursor = cnx.cursor()
   cursor.execute("""
      select 3 from your_table
   """)
   result = cursor.fetchall()
   print result
finally:
    cnx.close()
Eric Leschinski
  • 123,728
  • 82
  • 382
  • 321
Mr. Napik
  • 4,953
  • 3
  • 22
  • 18
  • 2
    Not quite as simple as you claim. When I tried to install the rpm I got a couple of dependency issues (FileDigests and PayloadIsXz) from my RPM: `rpm -i mysql-connector-python-1.1.5-1.el6.noarch.rpm` `error: Failed dependencies:` `rpmlib(FileDigests) <= 4.6.0-1 is needed by mysql-connector-python-1.1.5-1.el6.noarch` `rpmlib(PayloadIsXz) <= 5.2-1 is needed by mysql-connector-python-1.1.5-1.el6.noarch` – tatlar Feb 06 '14 at 18:43
  • Please in this case try the platform independent version (which requires a command line command to install ... bit trickier than double click), these seem to dependencies caused by the packaging. – Mr. Napik Feb 17 '14 at 18:48
  • 2
    I used to prefer this library, but it's no longer officially supported on PyPi. I've since moved to MySQLdb. – Steven Mercatante Sep 10 '14 at 17:59
  • 2
    @Arms: no longer officially supported on PyPi? Do you have any source for this? – Messa Jan 31 '15 at 16:09
  • I switched to this module for the timezone support – kommradHomer Feb 26 '15 at 09:50
  • 1
    You need to _register_ for this? :/ – J0hnG4lt Mar 26 '15 at 17:16
  • You don't need to register. I believe there is a "No thanks, just start my download" link a bit further down on the page.@J0hnG4lt – Johan May 22 '15 at 14:20
  • 8
    `pip install mysql-connector-python` will also work. I don't see where it says no longer supported on PyPi? Great if you don't have access to the gcc/C compilers on your system, and therefore can't install `mysqldb`. – decvalts Aug 07 '15 at 09:03
  • Super easy install, works great. Installed with: sudo pip install --egg mysql-connector-python-rf – TimH - Codidact Feb 24 '16 at 21:02
  • As someone already mentioned, pip also works. If for some reason pip refuses to install it via `pip install mysql-connector-python`, please check the top answer [here](http://stackoverflow.com/questions/34489271/i-cannot-install-mysql-connector-python-using-pip) (i.e. get it directly from MySQL's CDN). – absay Jul 27 '16 at 00:28
  • You can also install it via pip directly from the zip files of releases like this `pip install https://github.com/mysql/mysql-connector-python/archive/2.2.1-m2.zip` The list of releases can be found here https://github.com/mysql/mysql-connector-python/releases – Gourneau Oct 05 '16 at 20:06
  • 9
    as of Nov 7, 2016, the package for pip is just mysql-connector, ```pip search mysql-connector``` to find the package name. answer from here: http://stackoverflow.com/a/22829966/2048266 – nommer Nov 08 '16 at 00:32
126

Oracle (MySQL) now supports a pure Python connector. That means no binaries to install: it's just a Python library. It's called "Connector/Python".

http://dev.mysql.com/downloads/connector/python/

After installations, you can see some usage examples here

Alon Barad
  • 420
  • 5
  • 14
Ken Brown
  • 1,261
  • 1
  • 8
  • 3
  • 1
    is this faster than using mysqldb? – alwbtc Aug 31 '13 at 21:20
  • 9
    Yes, it is. Also, it's less hassle than MySQLdb and the API is better in my opinion. This should be the answer. – Anthony Dec 22 '13 at 14:44
  • 1
    using the official mysql connector of python is the best way to win time – Anas Apr 17 '14 at 01:09
  • Agree that Connector/Python works well, was easier to set up than MySQLdb, and has great documentation, as Karthic referenced above. And it supports Python 3, which MySQLdb does not (yet). – twasbrillig Apr 17 '14 at 23:55
  • You need to _register_ for this? :/ – J0hnG4lt Mar 26 '15 at 17:16
  • 2
    @J0hnG4lt You can just click on "No thanks, just start my download" below the login form (which actually seems mandatory, but isn't). – ComFreek May 22 '15 at 10:28
  • 6
    @ComFreek great. How is that better? Can we stop applying the "Windows workflow". Package management exists. – J0hnG4lt May 22 '15 at 10:51
  • The above examples link is broken, you may use - https://dev.mysql.com/doc/connector-python/en/connector-python-examples.html – San Dec 13 '16 at 04:33
121

Stop Using MySQLDb if you want to avoid installing mysql headers just to access mysql from python.

Use pymysql. It does all of what MySQLDb does, but it was implemented purely in Python with NO External Dependencies. This makes the installation process on all operating systems consistent and easy. pymysql is a drop in replacement for MySQLDb and IMHO there is no reason to ever use MySQLDb for anything... EVER! - PTSD from installing MySQLDb on Mac OSX and *Nix systems, but that's just me.

Installation

pip install pymysql

That's it... you are ready to play.

Example usage from pymysql Github repo

import pymysql.cursors
import pymysql

# Connect to the database
connection = pymysql.connect(host='localhost',
                             user='user',
                             password='passwd',
                             db='db',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

try:
    with connection.cursor() as cursor:
        # Create a new record
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('webmaster@python.org', 'very-secret'))

    # connection is not autocommit by default. So you must commit to save
    # your changes.
    connection.commit()

    with connection.cursor() as cursor:
        # Read a single record
        sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
        cursor.execute(sql, ('webmaster@python.org',))
        result = cursor.fetchone()
        print(result)
finally:
    connection.close()

ALSO - Replace MySQLdb in existing code quickly and transparently

If you have existing code that uses MySQLdb, you can easily replace it with pymysql using this simple process:

# import MySQLdb << Remove this line and replace with:
import pymysql
pymysql.install_as_MySQLdb()

All subsequent references to MySQLdb will use pymysql transparently.

Phillip
  • 1,969
  • 1
  • 22
  • 38
OkezieE
  • 4,575
  • 3
  • 23
  • 24
  • 3
    "Always" is a little strong... What is wrong with peewee or sqlalchemy? Even if they do exist as ORM libraries, they are still just as useful – OneCricketeer Feb 10 '16 at 01:30
  • 4
    No I don't think it's strong at all. Given the option to use either MySQLDb or PyMysql I think choosing PyMysql is a no brainer because it is a simple pip install with no dependencies, while MySQLDb requires mysql development header files to be installed for your OS platform for it to work. Sqlalchemy doesn't factor into this because it still needs to wrap around a module that can talk to mysql like PyMysql, MySQLDb, CyMySQL e.t.c. Peewee looks interesting though, I'll check that out – OkezieE Feb 10 '16 at 15:01
  • 2
    @cricket_007 peewee and sqlalchemly don't implement their own db connector, they provide a layer above MySQLdb etc. – rocksportrocker Jul 04 '17 at 07:44
  • I am getting this error when trying to connect to AWS RDS mariadb using pymysql. `OperationalError: (1045, "Access denied for user 'admin'@'pool-96-107-103.bstnma.fios.verizon.net' (using password: YES)")` – Murtaza Haji Jun 17 '20 at 13:12
  • 1
    @MurtazaHaji you will get that error with any mysql client if you enter incorrect credentials. Check your credentials. – OkezieE Jun 17 '20 at 14:38
  • Use this library if working with Python3.6+ – oz19 May 17 '21 at 15:18
24

Try using MySQLdb. MySQLdb only supports Python 2.

There is a how to page here: http://www.kitebird.com/articles/pydbapi.html


From the page:

# server_version.py - retrieve and display database server version

import MySQLdb

conn = MySQLdb.connect (host = "localhost",
                        user = "testuser",
                        passwd = "testpass",
                        db = "test")
cursor = conn.cursor ()
cursor.execute ("SELECT VERSION()")
row = cursor.fetchone ()
print "server version:", row[0]
cursor.close ()
conn.close ()
Flimm
  • 97,949
  • 30
  • 201
  • 217
Hortitude
  • 12,632
  • 16
  • 54
  • 71
17

As a db driver, there is also oursql. Some of the reasons listed on that link, which say why oursql is better:

  • oursql has real parameterization, sending the SQL and data to MySQL completely separately.
  • oursql allows text or binary data to be streamed into the database and streamed out of the database, instead of requiring everything to be buffered in the client.
  • oursql can both insert rows lazily and fetch rows lazily.
  • oursql has unicode support on by default.
  • oursql supports python 2.4 through 2.7 without any deprecation warnings on 2.6+ (see PEP 218) and without completely failing on 2.7 (see PEP 328).
  • oursql runs natively on python 3.x.

So how to connect to mysql with oursql?

Very similar to mysqldb:

import oursql

db_connection = oursql.connect(host='127.0.0.1',user='foo',passwd='foobar',db='db_name')
cur=db_connection.cursor()
cur.execute("SELECT * FROM `tbl_name`")
for row in cur.fetchall():
    print row[0]

The tutorial in the documentation is pretty decent.

And of course for ORM SQLAlchemy is a good choice, as already mentioned in the other answers.

bool.dev
  • 16,879
  • 5
  • 62
  • 90
  • 5
    I don't understand the 'runs natively on python 3.x'. I just tried to install it and the setup.py bombs out because it doesn't even use Python 3 compatible print calls. Sounded great until I actually tried it. – otakucode Oct 12 '15 at 16:16
15

Run this command in your terminal to install mysql connector:

pip install mysql-connector-python

And run this in your python editor to connect to MySQL:

import mysql.connector

mydb = mysql.connector.connect(
      host="localhost",
      user="yusername",
      passwd="password",
      database="database_name"
)

Samples to execute MySQL Commands (in your python edior):

mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")    
mycursor.execute("SHOW TABLES")

mycursor.execute("INSERT INTO customers (name, address) VALUES ('John', 'Highway 21')")    
mydb.commit() # Use this command after insert or update

For more commands: https://www.w3schools.com/python/python_mysql_getstarted.asp

Scott
  • 2,415
  • 3
  • 21
  • 38
  • Can you please answer this?? It is related to `mysql-connector` only. https://stackoverflow.com/questions/59405740/my-program-is-not-being-able-to-store-values-in-mysql-using-mysql-connector-lib –  Dec 19 '19 at 08:26
  • 3
    Some guys already answered your question there. You just forgot to run `mydb.commit()` after inserting values into table – Scott Dec 19 '19 at 10:39
13

SqlAlchemy


SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL. SQLAlchemy provides a full suite of well known enterprise-level persistence patterns, designed for efficient and high-performing database access, adapted into a simple and Pythonic domain language.

Installation

pip install sqlalchemy

RAW query

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session

engine = create_engine("mysql://<user_name>:<password>@<host_name>/<db_name>")
session_obj = sessionmaker(bind=engine)
session = scoped_session(session_obj)

# insert into database
session.execute("insert into person values(2, 'random_name')")
session.flush()
session.commit()

ORM way

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session

Base = declarative_base()
engine = create_engine("mysql://<user_name>:<password>@<host_name>/<db_name>")
session_obj = sessionmaker(bind=engine)
session = scoped_session(session_obj)

# Bind the engine to the metadata of the Base class so that the
# declaratives can be accessed through a DBSession instance
Base.metadata.bind = engine

class Person(Base):
    __tablename__ = 'person'
    # Here we define columns for the table person
    # Notice that each column is also a normal Python instance attribute.
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)

# insert into database
person_obj = Person(id=12, name="name")
session.add(person_obj)
session.flush()
session.commit()
Anand Tripathi
  • 8,458
  • 1
  • 30
  • 38
11

Despite all answers above, in case you do not want to connect to a specific database upfront, for example, if you want to create the database still (!), you can use connection.select_db(database), as demonstrated in the following.

import pymysql.cursors
connection = pymysql.connect(host='localhost',
                         user='mahdi',
                         password='mahdi',
                         charset='utf8mb4',
                         cursorclass=pymysql.cursors.DictCursor)
cursor = connection.cursor()
cursor.execute("CREATE DATABASE IF NOT EXISTS "+database)
connection.select_db(database)
sql_create = "CREATE TABLE IF NOT EXISTS "+tablename+(timestamp DATETIME NOT NULL PRIMARY KEY)"
cursor.execute(sql_create)
connection.commit()
cursor.close()
Mahdi
  • 1,646
  • 19
  • 30
11

Best way to connect to MySQL from python is to Use MySQL Connector/Python because it is official Oracle driver for MySQL for working with Python and it works with both Python 3 and Python 2.

follow the steps mentioned below to connect MySQL

  1. install connector using pip

    pip install mysql-connector-python

or you can download the installer from https://dev.mysql.com/downloads/connector/python/

  1. Use connect() method of mysql connector python to connect to MySQL.pass the required argument to connect() method. i.e. Host, username, password, and database name.

  2. Create cursor object from connection object returned by connect()method to execute SQL queries.

  3. close the connection after your work completes.

Example:

import mysql.connector
 from mysql.connector import Error
 try:
     conn = mysql.connector.connect(host='hostname',
                         database='db',
                         user='root',
                         password='passcode')
     if conn.is_connected():
       cursor = conn.cursor()
       cursor.execute("select database();")
       record = cursor.fetchall()
       print ("You're connected to - ", record)
 except Error as e :
    print ("Print your error msg", e)
 finally:
    #closing database connection.
    if(conn.is_connected()):
       cursor.close()
       conn.close()

Reference - https://pynative.com/python-mysql-database-connection/

Important API of MySQL Connector Python

  • For DML operations - Use cursor.execute() and cursor.executemany() to run query. and after this use connection.commit() to persist your changes to DB

  • To fetch data - Use cursor.execute() to run query and cursor.fetchall(), cursor.fetchone(), cursor.fetchmany(SIZE) to fetch data

Vishal Hule
  • 648
  • 1
  • 7
  • 16
8

Even though some of you may mark this as a duplicate and get upset that I am copying someone else's answer, I would REALLY like to highlight an aspect of Mr. Napik's response. Because I missed this, I caused nationwide website downtime (9min). If only someone shared this information, I could have prevented it!

Here is his code:

import mysql.connector    
cnx = mysql.connector.connect(user='scott', password='tiger',
                              host='127.0.0.1',
                              database='employees')
try:
   cursor = cnx.cursor()
   cursor.execute("""select 3 from your_table""")
   result = cursor.fetchall()
   print(result)
finally:
    cnx.close()

The important thing here is the Try and Finally clause. This allows connections to ALWAYS be closed, regardless of what happens in the cursor/sqlstatement portion of the code. A lot of active connections cause DBLoadNoCPU to spike and could crash a db server.

I hope this warning helps to save servers and ultimately jobs! :D

Tanner Clark
  • 453
  • 6
  • 15
7

MySQLdb is the straightforward way. You get to execute SQL queries over a connection. Period.

My preferred way, which is also pythonic, is to use the mighty SQLAlchemy instead. Here is a query related tutorial, and here is a tutorial on ORM capabilities of SQLALchemy.

muhuk
  • 14,633
  • 7
  • 50
  • 93
7

for Python3.6 I found two driver: pymysql and mysqlclient. I tested the performance between them and got the result: the mysqlclient is faster.

below is my test process(need install python lib profilehooks to analyze time elapse:

raw sql: select * from FOO;

immediatly execute in mysql terminal: 46410 rows in set (0.10 sec)

pymysql (2.4s):

from profilehooks import profile
import pymysql.cursors
import pymysql
connection = pymysql.connect(host='localhost', user='root', db='foo')
c = connection.cursor()

@profile(immediate=True)
def read_by_pymysql():
    c.execute("select * from FOO;")
    res = c.fetchall()

read_by_pymysql()

here's the pymysql profile: enter image description here


mysqlclient (0.4s)

from profilehooks import profile
import MySQLdb

connection = MySQLdb.connect(host='localhost', user='root', db='foo')
c = connection.cursor()

@profile(immediate=True)
def read_by_mysqlclient():
    c.execute("select * from FOO;")
    res = c.fetchall()

read_by_mysqlclient()

here's the mysqlclient profile: enter image description here

So, it seems that mysqlclient is much faster than pymysql

kai
  • 775
  • 9
  • 9
4

Just a modification in above answer. Simply run this command to install mysql for python

sudo yum install MySQL-python
sudo apt-get install MySQL-python

remember! It is case sensitive.

Hafiz Muhammad Shafiq
  • 6,781
  • 10
  • 49
  • 92
  • I installed MySQL-python via yum install. The installation was complete but I cannot import the MySQLdb module. It says no such module. Any idea why is it so? – user3527975 Mar 02 '16 at 05:57
  • It's not clear which answer you mean when you say "above answer". Please make your answer complete in itself. If you want to refer to other answers, please link to the specific answer. – Flimm Apr 18 '19 at 09:47
4

mysqlclient is the best as others only provide support to specific versions of python

 pip install mysqlclient

example code

    import mysql.connector
    import _mysql
    db=_mysql.connect("127.0.0.1","root","umer","sys")
    #db=_mysql.connect(host,user,password,db)
    # Example of how to insert new values:
    db.query("""INSERT INTO table1 VALUES ('01', 'myname')""")
    db.store_result()
    db.query("SELECT * FROM new1.table1 ;") 
    #new1 is scheme table1 is table mysql 
    res= db.store_result()
    for i in range(res.num_rows()):
        print(result.fetch_row())

see https://github.com/PyMySQL/mysqlclient-python

Umer
  • 937
  • 10
  • 24
  • 1
    +1 for proposing the fastest solution for python 3. However, `mysql.connector` and `_mysql` give both an import error (though the second option should work according to the documentation). `import MySQLdb` works, and then `MySQLdb.connect...` – Suzana May 16 '19 at 12:59
3

Also take a look at Storm. It is a simple SQL mapping tool which allows you to easily edit and create SQL entries without writing the queries.

Here is a simple example:

from storm.locals import *

# User will be the mapped object; you have to create the table before mapping it
class User(object):
        __storm_table__ = "user" # table name
        ID = Int(primary=True) #field ID
        name= Unicode() # field name

database = create_database("mysql://root:password@localhost:3306/databaseName")
store = Store(database)

user = User()
user.name = u"Mark"

print str(user.ID) # None

store.add(user)  
store.flush() # ID is AUTO_INCREMENT

print str(user.ID) # 1 (ID)

store.commit() # commit all changes to the database

To find and object use:

michael = store.find(User, User.name == u"Michael").one()
print str(user.ID) # 10

Find with primary key:

print store.get(User, 1).name #Mark

For further information see the tutorial.

michip96
  • 351
  • 1
  • 12
2

This is Mysql DB connection

from flask import Flask, render_template, request
from flask_mysqldb import MySQL

app = Flask(__name__)


app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'root'
app.config['MYSQL_DB'] = 'MyDB'

mysql = MySQL(app)


@app.route('/', methods=['GET', 'POST']) 
def index():
    if request.method == "POST":
        details = request.form
        cur = mysql.connection.cursor()
        cur.execute ("_Your query_")
        mysql.connection.commit()
        cur.close()
        return 'success'
    return render_template('index.html')


if __name__ == '__main__':
    app.run()
Aditya
  • 1,369
  • 9
  • 19
1

you can connect your python code to mysql in this way.

import MySQLdb
db = MySQLdb.connect(host="localhost",
                 user="appuser",
                 passwd="",
                 db="onco")

cursor = db.cursor()
Haider Ali
  • 47
  • 7
1

PyMySQL 0.10.1 - Released: Sep 10, 2020, has support for python3 as well.

python3 -m pip install PyMySQL

Simple code:

import pymysql

# Connect to the database
conn = pymysql.connect(host='127.0.0.1',user='root',passwd='root',db='fax')

# Create a Cursor object
cur = conn.cursor()

# Execute the query
cur.execute("SELECT * FROM fax.student")

# Read and print records
for row in cur.fetchall():
    print(row)

output:

(1, 'Petar', 'Petrovic', 1813, 'Njegusi')
(2, 'Donald', 'Tramp', 1946, 'New York')
(3, 'Bill', 'Gates', 1955, 'Seattle')
Milovan Tomašević
  • 1,206
  • 1
  • 7
  • 13
0

For python 3.3

CyMySQL https://github.com/nakagami/CyMySQL

I have pip installed on my windows 7, just pip install cymysql

(you don't need cython) quick and painless

Lazik
  • 2,214
  • 2
  • 21
  • 29
0

first install the driver

pip install MySQL-python   

Then a basic code goes like this:

#!/usr/bin/python
import MySQLdb

try:
    db = MySQLdb.connect(host="localhost",      # db server, can be a remote one 
                     db="mydb"                  # database
                     user="mydb",               # username
                     passwd="mydb123",          # password for this username
                     )        

    # Create a Cursor object
    cur = db.cursor()

    # Create a query string. It can contain variables
    query_string = "SELECT * FROM MY_TABLE"

    # Execute the query
    cur.execute(query_string)

    # Get all the rows present the database
    for each_row in cur.fetchall():
        print each_row

    # Close the connection
    db.close()
except Exception, e:
    print 'Error ', e 
Vishvajit Pathak
  • 2,313
  • 17
  • 15
0

First install the driver (Ubuntu)

  • sudo apt-get install python-pip

  • sudo pip install -U pip

  • sudo apt-get install python-dev libmysqlclient-dev

  • sudo apt-get install MySQL-python

MySQL database connection codes

import MySQLdb
conn = MySQLdb.connect (host = "localhost",user = "root",passwd = "pass",db = "dbname")
cursor = conn.cursor ()
cursor.execute ("SELECT VERSION()")
row = cursor.fetchone ()
print "server version:", row[0]
cursor.close ()
conn.close ()
Hasib Kamal
  • 1,971
  • 20
  • 26
0

First step to get The Library: Open terminal and execute pip install mysql-python-connector. After the installation go the second step.

Second Step to import the library: Open your python file and write the following code: import mysql.connector

Third step to connect to the server: Write the following code:

conn = mysql.connector.connect(host=you host name like localhost or 127.0.0.1, username=your username like root, password = your password)

Third step Making the cursor: Making a cursor makes it easy for us to run queries. To make the cursor use the following code: cursor = conn.cursor()

Executing queries: For executing queries you can do the following: cursor.execute(query)

If the query changes any thing in the table you need to add the following code after the execution of the query: conn.commit()

Getting values from a query: If you want to get values from a query then you can do the following: cursor.excecute('SELECT * FROM table_name') for i in cursor: print(i) #Or for i in cursor.fetchall(): print(i)

The fetchall() method returns a list with many tuples that contain the values that you requested ,row after row .

Closing the connection: To close the connection you should use the following code: conn.close()

Handling exception: To Handel exception you can do it Vai the following method: try: #Logic pass except mysql.connector.errors.Error: #Logic pass To use a database: For example you are a account creating system where you are storing the data in a database named blabla, you can just add a database parameter to the connect() method ,like

mysql.connector.connect(database = database name)

don't remove other informations like host,username,password.

Code GUI
  • 11
  • 2
0

A very good connector for MySQL and MariaDB is mysql-connector-python. It is written in Python so you can modify it whenever you want.

You can install it by running these commands:

pip3 uninstall mysql-connector
pip3 install mysql-connector-python

Then you can use it with the following code:

import mysql.connector

database = mysql.connector.connect(
    host='localhost',
    user='db_username,
    password='passwd',
    database='db_name',
    autocommit=True
)
cursor = database.cursor()

cursor.execute('SELECT * FROM users')

You can pass the autocommit parameter and set it to True. In this way you will not have to call database.commit() every time you update the database. Also you can prevent some errors I have mentioned in another question.

External links

  1. Python MySQL Connector
  2. SQL (Structured Query Language)
manarinian
  • 199
  • 9
0

Another option if you just want to plot some data from the database is to use the Jupyter kernel, it is designed for MariaDB, but it should easily work on MySQL too.

robert
  • 11
  • 2
-3

First, install python-mysql connector from https://dev.mysql.com/downloads/connector/python/

on Python console enter:

pip install mysql-connector-python-rf
import mysql.connector
Suraj Rao
  • 28,186
  • 10
  • 88
  • 94
  • 2
    The question was a little too broad, but this answer seems to be a bit too narrow (at least in the sense that installing and importing a module alone won't do). There also seems to be shell and python intermixed in single code block without any explanation or hints wrt what goes where and does what. – Ondrej K. Jun 08 '18 at 15:37