aioMySQL 未与 python 连接
Posted
技术标签:
【中文标题】aioMySQL 未与 python 连接【英文标题】:aioMySQL not connecting with python 【发布时间】:2020-03-27 02:24:22 【问题描述】:我知道这有点重复,但我已经查看了互联网的每一个角落,但我似乎找不到解决这个问题的方法。基本上,我正在尝试通过 aiomysql 连接到 mySQL 数据库。我的脚本太长了,无法放入,但它能够很好地连接到已经设置好的 mySQL/phpMyAdmin。当我运行它尝试连接到新数据库时,我得到了
Task exception was never retrieved
future: <Task finished name='Task-1' coro=<database.createPool() done, defined at /home/blackcoffee/Desktop/Code/She11Sh0ck/dbhandler.py:13> exception=OperationalError(2003, "Can't connect to MySQL server on 'X.X.X.X'")>
Traceback (most recent call last):
File "/home/blackcoffee/.local/lib/python3.8/site-packages/aiomysql/connection.py", line 486, in _connect
self._reader, self._writer = await \
File "/usr/lib/python3.8/asyncio/tasks.py", line 455, in wait_for
return await fut
File "/usr/lib/python3.8/asyncio/streams.py", line 52, in open_connection
transport, _ = await loop.create_connection(
File "/usr/lib/python3.8/asyncio/base_events.py", line 1017, in create_connection
raise exceptions[0]
File "/usr/lib/python3.8/asyncio/base_events.py", line 1002, in create_connection
sock = await self._connect_sock(
File "/usr/lib/python3.8/asyncio/base_events.py", line 916, in _connect_sock
await self.sock_connect(sock, address)
File "/usr/lib/python3.8/asyncio/selector_events.py", line 485, in sock_connect
return await fut
File "/usr/lib/python3.8/asyncio/selector_events.py", line 517, in _sock_connect_cb
raise OSError(err, f'Connect call failed address')
ConnectionRefusedError: [Errno 111] Connect call failed ('X.X.X.X', 3306)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/blackcoffee/Desktop/Code/She11Sh0ck/dbhandler.py", line 15, in createPool
self.pool = await aiomysql.create_pool(
File "/home/blackcoffee/.local/lib/python3.8/site-packages/aiomysql/pool.py", line 29, in _create_pool
await pool._fill_free_pool(False)
File "/home/blackcoffee/.local/lib/python3.8/site-packages/aiomysql/pool.py", line 167, in _fill_free_pool
conn = await connect(echo=self._echo, loop=self._loop,
File "/home/blackcoffee/.local/lib/python3.8/site-packages/aiomysql/connection.py", line 75, in _connect
await conn._connect()
File "/home/blackcoffee/.local/lib/python3.8/site-packages/aiomysql/connection.py", line 521, in _connect
raise OperationalError(2003,
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'X.X.X.X'")
查看我服务器上的一些细节,
mysqladmin Ver 8.42 Distrib 5.7.29, for Linux on x86_64
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Server version 5.7.29-0ubuntu0.18.04.1
Protocol version 10
Connection Localhost via UNIX socket
UNIX socket /var/run/mysqld/mysqld.sock
Uptime: 5 min 26 sec
Threads: 1 Questions: 4 Slow queries: 0 Opens: 105 Flush tables: 1 Open tables: 98 Queries per second avg: 0.012
最后,我知道我的 root 密码是正确的,因为我可以使用它毫无问题地登录 phpMyAdmin。任何帮助将不胜感激。
进度更新:我通过将绑定地址更改为 0.0.0.0 来连接它,但现在它给了我另一个错误。这是处理数据库和错误的代码。
import asyncio
import aiomysql
from creds import getdb
# Connect to server
class database:
def __init__(self):
print("SQL DB STARTED")
async def createPool(self, loop):
dbcreds = getdb()
self.pool = await aiomysql.create_pool(
host=dbcreds["host"],
port=dbcreds["port"],
user=dbcreds["user"],
password=dbcreds["password"],
db=dbcreds["db"],
loop=loop,
)
async def getUserCTFID(self, discordID, guildID):
sql = "SELECT activectf FROM members where `uuid` = %d and `guildid` = %d" % (
int(discordID),
int(guildID),
)
async with self.pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(sql)
(r) = await cur.fetchone()
return r[0]
# self.pool.close()
# await self.pool.wait_closed()
async def getCTFID(self, name, guildID):
sql = "SELECT ctfid FROM ctfs where `name` = '' and `guildid` = ''".format(
str(name), int(guildID),
)
async with self.pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(sql)
(r) = await cur.fetchone()
return r[0]
async def getCTFName(self, CTFID):
sql = "SELECT name FROM ctfs where `ctfid` = %d" % (int(CTFID))
async with self.pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(sql)
(r) = await cur.fetchone()
return r[0]
# self.pool.close()
# wait self.pool.wait_closed()
async def getCTFQuestions(self, CTFID):
sql = "SELECT name,Solved FROM ctfQuestions where `ctfid` = %d" % (int(CTFID))
async with self.pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(sql)
(r) = await cur.fetchall()
return r
# self.pool.close()
# await self.pool.wait_closed()
async def getValidCTFIDs(self, DiscordID, GuildID):
sql = "SELECT ctfs.ctfid,ctfs.name FROM members INNER JOIN ctfs ON ctfs.guildid=members.guildid WHERE ctfs.guildid = members.guildid and members.uuid = and members.guildid = ".format(
int(DiscordID), int(GuildID)
)
async with self.pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(sql)
(r) = await cur.fetchall()
return r
# self.pool.close()
# await self.pool.wait_closed()
async def updateCTF(self, DiscordID, GuildID, CTFID):
sql = "UPDATE `members` SET `activectf`= WHERE uuid= and guildid=".format(
int(CTFID), int(DiscordID), int(GuildID)
)
async with self.pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(sql)
await conn.commit()
# self.pool.close()
# await self.pool.wait_closed()
async def createCTF(self, ctfName, guildID):
print(ctfName)
sql = "INSERT INTO ctfs (name, guildid) VALUES ('','')".format(
str(ctfName), int(guildID)
)
async with self.pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(sql)
await conn.commit()
async def deleteCTF(self, ctfName, guildID):
print("Goodbye ".format(ctfName))
sql = "DELETE FROM `ctfs` WHERE name = '' and guildid = ''".format(
str(ctfName), int(guildID)
)
async with self.pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(sql)
await conn.commit()
# self.pool.close()
# await self.pool.wait_closed()
async def getGuildByID(self, guildid):
sql = "SELECT guildid, guildname from guilds where guildid=".format(
int(guildid)
)
async with self.pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(sql)
return await cur.fetchone()
# self.pool.close()
# await self.pool.wait_closed()
async def getMember(self, uuid, guildid):
sql = "SELECT id from members where uuid = and guildid=".format(
int(uuid), int(guildid)
)
async with self.pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(sql)
return await cur.fetchone()
# self.pool.close()
# await self.pool.wait_closed()
async def addMember(self, uuid, guildid):
sql = "INSERT INTO members (uuid,guildid, activectf) VALUES ('','','')".format(
int(uuid), int(guildid), 0
)
async with self.pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(sql)
await conn.commit()
# self.pool.close()
# await self.pool.wait_closed()
async def addGuild(self, guildid, guildname):
sql = "INSERT INTO guilds (guildid, guildname) VALUES ('','')".format(
int(guildid), str(guildname)
)
print(sql)
async with self.pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(sql)
await conn.commit()
# self.pool.close()
# await self.pool.wait_closed()
async def addQuestion(self, questionName, CTFID):
sql = "INSERT INTO ctfQuestions (name, ctfid, Solved) VALUES ('','', '')".format(
str(questionName), int(CTFID), 0
)
async with self.pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(sql)
await conn.commit()
# self.pool.close()
# await self.pool.wait_closed()
async def updateQuestionState(self, questionName, CTFID, state):
sql = "UPDATE `ctfQuestions` SET `Solved`='' WHERE name='' and CTFID=''".format(
int(state), str(questionName), int(CTFID)
)
async with self.pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(sql)
await conn.commit()
# self.pool.close()
# await self.pool.wait_closed()
async def setSolved(self, questionName, CTFID):
await self.updateQuestionState(questionName, CTFID, 1)
async def setUnsolved(self, questionName, CTFID):
await self.updateQuestionState(questionName, CTFID, 0)
async def delQuestion(self, questionName, CTFID):
sql = "DELETE FROM `ctfQuestions` WHERE name='' and CTFID='' ".format(
str(questionName), int(CTFID)
)
async with self.pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(sql)
await conn.commit()
# self.pool.close()
# await self.pool.wait_closed()
An open stream object is being garbage collected; call "stream.close()" explicitly.
Exception ignored in: <coroutine object Connection._get_server_information at 0x7fedfa7be6c0>
Traceback (most recent call last):
File "/home/blackcoffee/.local/lib/python3.8/site-packages/aiomysql/connection.py", line 989, in _get_server_information
packet = await self._read_packet()
File "/home/blackcoffee/.local/lib/python3.8/site-packages/aiomysql/connection.py", line 561, in _read_packet
packet_header = await self._read_bytes(4)
File "/home/blackcoffee/.local/lib/python3.8/site-packages/aiomysql/connection.py", line 599, in _read_bytes
except asyncio.streams.IncompleteReadError as e:
AttributeError: module 'asyncio.streams' has no attribute 'IncompleteReadError'
Task was destroyed but it is pending!
task: <Task pending name='Task-1' coro=<database.createPool() running at /home/blackcoffee/Desktop/Code/She11Sh0ck/dbhandler.py:15> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x7fedf9624ee0>()]>>
老实说,我不知道如何理解这个错误
选择@@thread_handling;给出:
+---------------------------+
| @@thread_handling |
+---------------------------+
| one-thread-per-connection |
+---------------------------+
1 row in set (0.00 sec)
【问题讨论】:
你能登录到你的 MySQL 获取客户端命令提示符吗,SELECT @@thread_handling;并发布结果? 刚刚添加@WilsonHauck 是否可以支持线程处理为“每个连接一个线程”的池?您能否发布 A) SHOW GLOBAL VARIABLES LIKE '%pool%' 的结果; B) SHOW 插件; @BlackCoffee 您的 SQL 查询容易受到 SQL 注入。始终使用参数化 SQL。 【参考方案1】:我觉得自己像个白痴。经过几天和几天的搜索,解决方案是允许来自我自己的 ip 的连接。
GRANT ALL ON *.* to <user>@<my_ip> IDENTIFIED BY <my_password>;
【讨论】:
以上是关于aioMySQL 未与 python 连接的主要内容,如果未能解决你的问题,请参考以下文章