How to use python 3.5.1 with a MySQL database

Awa Melvine picture Awa Melvine · Feb 28, 2016 · Viewed 58.1k times · Source

I have been trying to use MySQL in a Python project I've been working on. I downloaded the connector: mysql-connector-python-2.1.3-py3.4-winx64 here.

I already had Python 3.5.1 installed. When I tried to install the connector, it didn't work because it required python 2.7 instead. I have searched on many sites, even on StackOverflow I couldn't find a solution.

Thanks for any help.

Answer

S0H31L picture S0H31L · Jun 9, 2016

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

  • Download driver from here
  • Driver installation in cmd, in this folder Python\Python35\PyMySQL-0.7.4\pymysql

    python setup.py build
    python setup.py install
    
  • Copy folder Python\Python35\PyMySQL-0.7.4\pymysql to Python\Python35\pymysql

  • 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!