How to use python 3.5.1 with a MySQL database

How to use python 3.5.1 with a MySQL database

I did the steps below with Python 3.5.1 and it works:

  • Download driver from here
  • Driver installation in cmd, in this folder
    PythonPython35PyMySQL-0.7.4pymysql

    python setup.py build
    python setup.py install
    
  • Copy folder PythonPython35PyMySQL-0.7.4pymysql to
    PythonPython35pymysql

  • Sample code in python IDE

    import pymysql
    import pymysql.cursors
    conn= pymysql.connect(host=localhost,user=user,password=user,db=testdb,charset=utf8mb4,cursorclass=pymysql.cursors.DictCursor)
    a=conn.cursor()
    sql=CREATE TABLE `users` (`id` int(11) NOT NULL AUTO_INCREMENT,`email` varchar(255) NOT NULL,`password` varchar(255) NOT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
    a.execute(sql)
    
  • Enjoy It!

I am using Python 3.5.2 on window 8 pro 64-bit and the following procedure is worked for me.

  1. Download driver (PyMySQL-0.7.9.tar.gz (md5)) from here

  2. Extract and copy the folder pymysql into the python Lib folder e.g (C:UsersMyUsernameAppDataLocalProgramsPythonPython35-32Lib)

  3. Copy and run the following example.py
#!/usr/bin/env python

import pymysql

conn = pymysql.connect(host=localhost, port=3306, user=root, passwd=, db=sandbox)

cur = conn.cursor()
cur.execute(SELECT * FROM users)

print(cur.description)
print()

for row in cur:
    print(row)

cur.close()
conn.close()

I hope it will work for you as well. Happy coding 🙂

How to use python 3.5.1 with a MySQL database

Visit this web site and you will find a mysqld package that works fine with Python 3 on Windows : http://www.lfd.uci.edu/~gohlke/pythonlibs/

Otherwise you can use pymysql which might be slower but works fine with Python 3.

Leave a Reply

Your email address will not be published.