Python 連接數據庫失敗
什麽是 PyMySQL?
PyMySQL 是在 Python3.x 版本中用於連接 MySQL 服務器的一個庫,Python2中則使用mysqldb。
PyMySQL 遵循 Python 數據庫 API v2.0 規範,並包含了 pure-Python MySQL 客戶端庫。
在使用 PyMySQL 之前,我們需要確保 PyMySQL 已安裝。
PyMySQL 下載地址:https://github.com/PyMySQL/PyMySQL。
如果還未安裝,我們可以使用以下命令安裝最新版的 PyMySQL:
$ pip3 install PyMySQL
以下實例鏈接 Mysql 的 TESTDB 數據庫:
#!/usr/bin/python3 import pymysql # 打開數據庫連接 db = pymysql.connect("localhost","testuser","test123","TESTDB" ) # 使用 cursor() 方法創建一個遊標對象 cursor cursor = db.cursor() # 使用 execute() 方法執行 SQL 查詢 cursor.execute("SELECT VERSION()") # 使用 fetchone() 方法獲取單條數據. data = cursor.fetchone() print ("Database version : %s" % data) # 關閉數據庫連接 db.close()
報錯如下:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pymysql/connections.py", line 582, in connect
**kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 727, in create_connection
raise err
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 716, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 61] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "mysql_conn.py", line 6, in <module>
db = pymysql.connect("localhost","root","201995zjh","ryan" )
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pymysql/__init__.py", line 94, in Connect
return Connection(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pymysql/connections.py", line 327, in __init__
self.connect()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pymysql/connections.py", line 629, in connect
raise exc
pymysql.err.OperationalError: (2003, "Can‘t connect to MySQL server on ‘localhost‘ ([Errno 61] Connection refused)")
在確定安裝了 PyMySQL 以及數據庫賬號密碼等沒有問題時,還是不能連接 MySQL,
最後只剩下兩種可能:
1. 運行 mysqladmin variables | grep socket 來獲取套接字所在的位置,並嘗試設置如下連接:
pymysql.connect(db=‘base‘, user=‘root‘, passwd=‘pwd‘, unix_socket="/tmp/mysql.sock")
2. 運行 mysqladmin variables | grep port 並驗證端口是3306.如果沒有,您可以手動設置端口,如下所示:
pymysql.connect(db=‘base‘, user=‘root‘, passwd=‘pwd‘, host=‘localhost‘, port=XXXX)
https://stackoverflow.com/questions/6885164/pymysql-cant-connect-to-mysql-on-localhost
Python 連接數據庫失敗