PyMySQL 是在 Python3.x 版本中用於鏈接 MySQL 服務器的一個庫,Python2中則使用mysqldb。python
PyMySQL 遵循 Python 數據庫 API v2.0 規範,幷包含了 pure-Python MySQL 客戶端庫。mysql
在使用 PyMySQL 以前,咱們須要確保 PyMySQL 已安裝。git
PyMySQL 下載地址:https://github.com/PyMySQL/PyMySQL。github
若是還未安裝,咱們能夠使用如下命令安裝最新版的 PyMySQL:sql
$ 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 refusedsocket
During handling of the above exception, another exception occurred:fetch
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)")spa
在肯定安裝了 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