Python Connect to MySQL
Posted Mr.zhou_Zxy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python Connect to MySQL相关的知识,希望对你有一定的参考价值。
Python Connect to mysql
一、install pymysql
pip install pymysql
二、Coding + Solve
Coding
import pymysql
DBHOST = 'ip'
DBPORT = 3306
DBUSER = 'root'
DBPASSWORD = 'root'
DBNAME = 'dbname'
db = pymysql.connect(host=DBHOST, port=DBPORT, user=DBUSER, password=DBPASSWORD, database=DBNAME)
cur = db.cursor(pymysql.cursors.DictCursor)
sql = 'select * from logs'
result = cur.execute(sql)
result = cur.fetchall()
print(result)
db.commit()
cur.close()
db.close()
print('查询成功!')
Problem
Traceback (most recent call last):
File "D:/date/PyCharm/djangoProject/demo/pymysql.py", line 1, in <module>
import pymysql
File "D:\\date\\PyCharm\\djangoProject\\demo\\pymysql.py", line 7, in <module>
db = pymysql.connect(host=DBHOST, port=DBPORT, user=DBUSER, password=DBPASSWORD, database=DBNAME)
AttributeError: module 'pymysql' has no attribute 'connect'
Re-Coding
import pymysql
if __name__ == '__main__':
DBHOST = '101.35.83.222'
DBPORT = 33060
DBUSER = 'root'
DBPASSWORD = '@Zhou147258369'
DBNAME = 'zxy'
db = pymysql.connect(host=DBHOST, port=DBPORT, user=DBUSER, password=DBPASSWORD, database=DBNAME)
cur = db.cursor(pymysql.cursors.DictCursor)
sql = 'select * from logs'
result = cur.execute(sql)
result = cur.fetchall()
print(result)
db.commit()
cur.close()
db.close()
print('查询成功!')
Problem
Traceback (most recent call last):
File "D:/date/PyCharm/djangoProject/demo/pymysql.py", line 8, in <module>
db = pymysql.connect(host=DBHOST, port=DBPORT, user=DBUSER, password=DBPASSWORD, database=DBNAME)
AttributeError: module 'pymysql' has no attribute 'connect'
Solve
最后发现原因在于,模块和文件名一致了
因为这个文件的名字也是pymysql导致的
调整为py_mysql.py
Result
['id': 1, 'log': 'zxy is created', 'id': 2, 'log': 'insert into user values (zxy)']
查询成功!
以上是关于Python Connect to MySQL的主要内容,如果未能解决你的问题,请参考以下文章
python 远程连接数据库显示can't connect to mysql server on 'lo... 解决方案
python 连接mysql 时,connect 出现错误,怎么解决
OperationalError: (2002, “Can't connect to local MySQL server through socket '/var/run/mysql
Mysql:is not allowed to connect to this MySQL server
报错:1130-host ... is not allowed to connect to this MySql server