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)'}]
查询成功!
|