0

How can I connect to MySQL in Windows 7 from an app written in Python 3.4.3?

I've been looking all around, but non seems to really work.

I did this:

C:\Users\Me>py -3.4 -m pip install P
Collecting PyMySQL
  Downloading PyMySQL-0.6.4-py2.py3-none
    100% |##############################
Installing collected packages: PyMySQL

Successfully installed PyMySQL-0.6.4

According to the message, it installed correctly, but still I get the below error:

>>> import MySQLdb
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    import MySQLdb
ImportError: No module named 'MySQLdb'

How can I make it work right? Thank you all in advance.

1
  • Ummm... MySQL and Python are two completely different pieces of software. Are you talking about a MySQL library for Python? Commented Feb 26, 2015 at 23:14

1 Answer 1

2

You are trying to import MySQLdb (which is not Python 3 compatible), but you are installing PyMySQL (which is). You've probably heard that PyMySQL is supposed to be a drop-in replacement for MySQLdb -- it is, but you need to do this first to tell it to impersonate MySQLdb. Add this to the beginning of your program, before the "import MySQLdb" line.

import pymysql
pymysql.install_as_MySQLdb()

You can put it behind a try/except ImportError guard so that the same source file works with either PyMySQL or MySQLdb installed.

An alternative would just be to remove any references to MySQLdb from your code and replace them with references to pymysql instead -- either way should work.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Andrew Gorcester. That's great advise. Let me read some more on your pointers. I'm sure it will be helpful. Thanks again :)
Great help, Andrew Gorcester. +1 +15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.