0

Getting connection error in PyMySQL:

Error

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='pymysql')
AttributeError: 'module' object has no attribute 'connect'

code

import pymysql

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='pymysql')

cur = conn.cursor()

cur.execute("SELECT Host,User FROM user")

print(cur.description)

print()

for row in cur:
   print(row)

cur.close()
conn.close()

5 Answers 5

3

Use capital 'C' in pymysql.Connect.

conn = pymysql.Connect(host='127.0.0.1', port=3306, user='root', passwd='', db='pymysql')

The above statement should work. It worked for me!

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

Comments

1

You've called some other module "pymysql". Look for a file named "pymysql.py" and rename it, and remove any associated .pyc file.

Comments

0

The connection was successful in this code:

con=pymysql.connect('localhost','root','root','mydb27')

But now I am following this code:

connection = pymysql.connect(host='localhost',
                             user='root',
                             password='kanha@12345',
                             database='mydb23',
                             charset='utf8mb4')
cur1=connection.cursor()
cur1.execute("select * from emp where city='hyd'")

1 Comment

What part is the correct answer? I'm confused as to what the answer is.
0

I had that error, due I named my py file as select.py. I don't know how you named it but you could try changing the name file.

Comments

0

In my case the problem was permissions - they were 700 and owned by root. This command fixed the problem:

sudo chmod -R 755 /usr/local/lib/python3.9/site-packages/pymysql

2 Comments

This kind of permissions problem is usually because you were not using a virtual environment (which you should always do) or you installed the package with sudo pip install ... (which you should avoid doing, and is avoided by using a virtual env)
This was on a transient aws instance. We normally do things as root since these are single -purpose VMs, but thanks for the tip. I'll have to change it to install this module as a user somehow. It gets installed automatically during deployment as root. Probably this will work: sudo -H -u ec2-user pip intall pymysql

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.