aioMySQL not connecting with python - python

I know this is somewhat of a duplicate, but I've looked in every nook and cranny of the internet and I can't seem to find the solution to this. Basically, I'm trying to connect to a mySQL database via aioMySQL. My Script is far too long to put in, but it was able to connect to an already setup mySQL/phpMyAdmin just fine. When I run it trying to connect to the new db, I get
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'")
Looking at some details on my server,
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
Lastly, I know my root password is correct because I can log in to phpMyAdmin with it with no problems. Any help would be greatly appreciated.
Progress Update: I got it to connect by changing the bind-address to 0.0.0.0, but now it's giving me another error. Here is the code to handle the db as well as the error.
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>()]>>
To be honest, I have no idea what to make of this error
SELECT ##thread_handling; gives:
+---------------------------+
| ##thread_handling |
+---------------------------+
| one-thread-per-connection |
+---------------------------+
1 row in set (0.00 sec)

I feel like such an idiot. After days and days of searching, the solution was to allow a connection from my own ip.
GRANT ALL ON *.* to <user>#<my_ip> IDENTIFIED BY <my_password>;

Related

Getting an error on sending an embed message of the player/user's balance

The following is the code that has to do with the balance, as u might notice that there are various currencies and for that I have done add_field quite a few times, it would be really nice if you could tell me if there is a way to do it in a shorter and/or easier way...anyways coming to the main problem.
Main.py
async def equilibrium(user: discord.Member):
db = await aiosqlite.connect("balance_db.db")
cursor = await db.cursor()
await cursor.execute(f"SELECT * FROM bal WHERE user_id = {user.id} ")
result = await cursour.fetchall()
print (result)
if result:
return
if not result:
await cursor.execute(f"INSERT INTO bal(user_id, cash, crystals, event_pearls, weapon_shards, fusion_earring, merging_stones, enhancing_stones) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", (user.id, 500, 0, 0, 0, 0, 0, 0, 0))
await db.commit()
await cursor.close()
await db.close()
#bot.command(aliases=['bal'])
async def balance(ctx, user:discord.Member=None):
if user is None:
user = ctx.author
await equilibrium(user=user)
db = await aiosqlite.connect("balance_db.db")
cursor = await db.cursor()
await cursor.execute(f"SELECT * FROM bal WHERE user_id = {user.id} ")
balem = discord.Embed(title=f"**{user.mention}'s balance**", color=discord.Color.blue())
balem.add_field(name="Cash:", value=f":GenesisCrystal: {result[1]}", inline=True)
balem.add_field(name="crystals:", value=f":GenesisCrystal: {result[2]}", inline=True)
balem.add_field(name="event pearls:", value=f":GenesisCrystal: {result[3]}", inline=True)
balem.add_field(name="weapon shards:", value=f":GenesisCrystal: {result[4]}", inline=True)
balem.add_field(name="fusion earring:", value=f":GenesisCrystal: {result[5]}", inline=True)
balem.add_field(name="merging stones:", value=f":GenesisCrystal: {result[6]}", inline=True)
balem.add_field(name="enhancing stones:", value=f":GenesisCrystal: {result[7]}", inline=True)
await ctx.send(embed=balem)
upon testing and doing '(serverprefix) bal' it gives the following error:
INFO discord.client logging in using static token
2022-09-12 23:45:43 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 7338538a9635f5cf39dba129dc8621fa).
[]
2022-09-12 23:45:44 ERROR discord.ext.commands.bot Ignoring exception in command balance
Traceback (most recent call last):
File "C:\Users\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 190, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Desktop\CodingPAIN.py", line 50, in balance
balem.add_field(name="Cash:", value=f":GenesisCrystal: {result[1]}", inline=True)
IndexError: list index out of range
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 986, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 199, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range
The Bot is Online
I am using the following:
python version 9.3x (9.3.13 precisely)
aiosqlite as the database (i know about the mordern aiosqlite method of writing the code, but I am much more familiar with the old, or the sqlite3 method
I am just a beginner, help of any kind would be appriciated
Looks like you need to change result = await cursor.fetchall() to result = await cursour.fetchall()[0].
Sqlite's fetchall() returns a list of tuples (something like [(1,), (2,)], so you need to index to the first tuple, then loop through that.

Discord.py and SQL - Comparing between 2 tables in the same database file

So I have two tables, Servers and Strikes. In the Servers table, I have a max strikes value. I want to compare the strikes a user has to the max strikes specified in the Servers table. I tried this:
#commands.command(name='strike', pass_ctx= True)
#commands.has_permissions(manage_messages=True)
async def strike(self, ctx, member : discord.Member):
first_strike = 1
cursor = await self.client.db.cursor()
await cursor.execute(f"SELECT Strikes_Have FROM Strikes WHERE Guild_ID = {ctx.guild.id} AND User_ID = {member.id}")
result = await cursor.fetchone()
if result == None:
cursor = await self.client.db.cursor()
sql = f"INSERT INTO Strikes(Guild_ID, User_ID, Strikes_Have) VALUES({ctx.guild.id}, {member.id}, {first_strike})"
else:
cursor = await self.client.db.cursor()
sql = f"UPDATE Strikes SET Strikes_Have = Strikes_Have + 1 where Guild_ID = {ctx.guild.id} AND User_ID = {member.id}"
if result["Strikes_Have"] == result["MAX_STRIKES"]:
await ctx.message.channel.send(f"{member} has the max amount of stirkes specified by the server")
await cursor.execute(sql)
await self.client.db.commit()
await cursor.close()
await ctx.message.channel.send(f"Striked {member}")`
But got this error:
Traceback (most recent call last):
File "/home/pi/.local/lib/python3.7/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/pi/EndorCore/cogs/Mod.py", line 225, in strike
if result["Strikes_Have"] == result["MAX_STRIKES"]:
IndexError: No item with that key
The error message you're getting currently is being caused by you trying to access a column of data which doesn't exist in the strikes table.
To get the max strikes value, you need to query that table and get the number, then compare the two.
For example:
cursor.execute(f"SELECT Strikes_Have FROM Strikes WHERE Guild_ID = {ctx.guild.id} AND User_ID = {member.id}")
user_result = cursor.fetchone()
cursor.execute(f"SELECT MAX_STRIKES FROM Servers WHERE Guild_ID = {ctx.guild.id}")
server_result = cursor.fetchone()
if user_result["Strikes_Have"] == server_result['MAX_STRIKES']:
print("User has max strikes")

How to store speacial symbols in SQLITE

This is my table
#client.event
async def on_ready():
db = sqlite3.connect('Smilewin.sqlite')
cursor = db.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS Introduce(
guild_id TEXT,
channel_id TEXT,
boarder TEXT,
status TEXT
)
''')
I wanted to store anything from a normal text to something like this ☆゚ ゜゚☆゚ ゜゚☆゚ ゜゚☆゚ ゜゚☆゚ ゜゚☆
(basically anything)
When I try to store ☆゚ ゜゚☆゚ ゜゚☆゚ ゜゚☆゚ ゜゚☆゚ ゜゚☆ It is giving an error.
Traceback (most recent call last):
File "C:\Users\ardil\Desktop\Desktop app\ANAPAH\Code\ReactV9\Smilewin-env\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\ardil\Desktop\Desktop app\ANAPAH\Code\ReactV9\SmileWinbot.py", line 618, in on_command_error
raise error
File "C:\Users\ardil\Desktop\Desktop app\ANAPAH\Code\ReactV9\Smilewin-env\lib\site-packages\discord\ext\commands\bot.py", line 902, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\ardil\Desktop\Desktop app\ANAPAH\Code\ReactV9\Smilewin-env\lib\site-packages\discord\ext\commands\core.py", line 864, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\ardil\Desktop\Desktop app\ANAPAH\Code\ReactV9\Smilewin-env\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'text'
The code which I use to store that special symbols is:
#client.command()
#commands.has_permissions(administrator=True)
async def setboarder(ctx, *,boarder):
db = sqlite3.connect('Smilewin.sqlite')
cursor = db.cursor()
cursor.execute(f"SELECT boarder FROM Introduce WHERE guild_id = {ctx.guild.id}")
result = cursor.fetchone
if result is None:
sql = ("INSERT INTO Introduce(guild_id, boarder) VALUES(?,?)")
val = (ctx.guild.id , boarder)
embed = discord.Embed(
colour= 0x00FFFF,
title = "ตั้งค่ากรอบเเนะนําตัว",
description= f"กรอบได้ถูกตั้งเป็น {boarder}"
)
message = await ctx.send(embed=embed)
await message.add_reaction('✅')
elif result is not None:
sql = ("UPDATE Introduce boarder = ? WHERE guild_id = ?")
val = (boarder , ctx.guild.id)
embed = discord.Embed(
colour= 0x00FFFF,
title = "ตั้งค่ากรอบเเนะนําตัว",
description= f"กรอบได้ถูกอัพเดตเป็น {boarder}"
)
message = await ctx.send(embed=embed)
await message.add_reaction('✅')
cursor.execute(sql, val)
db.commit()
cursor.close()
db.close()
I want to know is it possible to store that kind of data in sqlite. If yes how can I do it please provide some example. thank you so much
There is an error in your update query which may or may not have some bearing on the problem.
"UPDATE Introduce boarder = ? WHERE guild_id = ?"
is missing the keyword SET. The statement should be:
"UPDATE Introduce SET boarder = ? WHERE guild_id = ?"
I don't see how the exception traceback relates to this problem. It also seems unrelated to whether the db can store your unicode strings; it can.
Try fixing this bug and see how you go.

How can i create a table on my sqlite database?

Thats my first python sql and im trying to code this bot i got this error:
SQL CODE
import sqlite3
...
#commands.Cog.listener()
async def on_message(self, message):
db = sqlite3.connect('banco.sqlite')
cursor = db.cursor()
cursor.execute(f'SELECT nome FROM banco WHERE nome = "{message.author.id}"')
result = cursor.fetchone()
if result is None:
sql = ('INSERT INTO banco(nome, dinheiro) VALUES(?, ?)')
val = (message.author.id, 0)
cursor.execute(sql, val)
db.comit()
cursor.close()
ERROR:
File "/Users/CIP/Documents/GitHub/economia/cogs/dinheiro.py", line 54, in on_message
cursor.execute(f'SELECT column1 FROM banco WHERE column1 = "{message.author.id}"')
sqlite3.OperationalError: no such table: banco
LINE 54
cursor.execute(f'SELECT nome FROM banco WHERE nome = "{message.author.id}"')

Auto reconnect postgresq database

I have the following code:
import psycopg2
conn = psycopg2.connect(database="****", user="postgres", password="*****", host="localhost", port="5432")
print ("Opened database successfully")
cur = conn.cursor()
cur.execute('''select * from xyz''')
print ("Table created successfully")
conn.commit()
conn.close()
Like this i have some 50 -60 complex queries, but problem is some times the postgre sql Database throws the below error
Traceback (most recent call last):
File "C:/Users/ruw2/Desktop/SQL.py", line 87, in <module>
cur.execute('''select * from xyz;''')
psycopg2.DatabaseError: server conn crashed?
server closed the connection unexpectedly.
This probably means the server terminated abnormally before or while processing the request.
Looks like the connection is lost, how can i auto connect the Postgre database
Appreciate your help
I would rely on decorators - retry and reconnect:
import psycopg2
from tenacity import retry, wait_exponential, stop_after_attempt
from typing import Callable
def reconnect(f: Callable):
def wrapper(storage: DbStorage, *args, **kwargs):
if not storage.connected():
storage.connect()
try:
return f(storage, *args, **kwargs)
except psycopg2.Error:
storage.close()
raise
return wrapper
class DbStorage:
def __init__(self, conn: string):
self._conn: string = conn
self._connection = None
def connected(self) -> bool:
return self._connection and self._connection.closed == 0
def connect(self):
self.close()
self._connection = psycopg2.connect(self._conn)
def close(self):
if self.connected():
# noinspection PyBroadException
try:
self._connection.close()
except Exception:
pass
self._connection = None
#retry(stop=stop_after_attempt(3), wait=wait_exponential())
#reconnect
def get_data(self): # pass here required params to get data from DB
# ..
cur = self._connection.cursor()
cur.execute('''select * from xyz''')
# ..
Catch the exception and reconnect:
while True:
conn = psycopg2.connect(database="****", user="postgres", password="*****", host="localhost", port="5432")
cur = conn.cursor()
try:
cur.execute('''select * from xyz''')
except psycopg2.OperationalError:
continue
break;

Categories

Resources