#databases
1 messages · Page 129 of 1
There's no difference. Execute just makes it compliant with SQL standard
Both do the same thing.
Right, that makes sense. Thanks.
If i initially made a table with a column set as SERIAL, is it possible to make it GENERATED ALWAYS AS IDENTITY with an alter statement?
I just read that the second option will prevent accidentally inserting values into that column
Code:
with open('book.json') as jsondata:
data = json.load(jsondata)
while True:
query = input("Enter query: ")
print(f"{Style.RESET_ALL}{Fore.GREEN}Name: {list(filter(lambda x:x['name']==query,data))}\n"
f"Monthly searches: {list(filter(lambda x:x['val']==query,data))}")
Printed out:
Name: [{'name': 'Peru', 'val': '27.100'}]
Monthly searches: []
I am trying to make a search kinda thing and i only want the item name and the item val single
Yes it's possible since it uses sequence internally
But you would have to drop the current sequence first before altering
is this done by dropping the <tablename>_<columnname>_seq i see when i do \d?
also, what would this query look like?
Yes would be that format
DROP SEQUENCE schema.sequence_name;
ALTER TABLE schema.t1 ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY (RESTART some_value);
your schema is probably public so just replace where I have schema with that
And some_value is what you want to resume from.
Also you might have to drop defaults first
right, thanks!
are these SERIALs and GENERATED ... actual datatypes like varchar/char?
ALTER TABLE schema.tablename COLUMN id DROP DEFAULT
Yes
But will be int or bigint
oh, makes sense
in the alter column, don't we use ADD for constraints though? but while creating a table, we pass in SERIAL in the place where we'd pass in a data type; which confused me
I'm not sure what you mean?
actually, i might've misunderstood ALTER
oh, and is there some way to convert text to lowercase or something before matching?
in case i have data that have uppercase characters, how would i query it if the input was all lowercase
You can use the lower () function
Yeah it's pretty good, although I don't use it as much
oh, why's that?
i'm taught mysql at school, but i chose postgres because everyone seems to recommend it for discord bots
and the graphs asyncpg has on their readme are impressive https://raw.githubusercontent.com/MagicStack/asyncpg/master/performance.png
Well that graph is only for the driver/module
And MySQL is also perfectly fine. A lot of people seem to hate it for what it was like in the past. And then sometimes it's the circles your in where if one says X is good then everyone just repeats that.
But I'm sure postgres isn't perfect either. Oracle would be the real beast in this comparison game 😅
oh that's true 😄
why is mysql hated though? what was it like before?
await db.execute("""UPDATE votes SET (count = count+1, timer = $2) WHERE id = $1""", user.id, str(datetime.utcnow()))```
any idea why it's giving me a asyncpg syntax error near =
this is from the discord.py server, are all this actually true?
although i don't see why they're listing "owned by oracle" as a disadvantage 
They fixed a lot of stuff in newer versions, and now use a different engine. People hating on it is like those hating PHP because they used it in pre PHP 5 days.
Yeah exactly, it's the mindset some people have and as I said some people just follow what others say.
Huh? MySQL is widely used across everywhere? It's certainly passed the test so I'm not sure where you get this from.
MySQL is rarely the problem for most people. It's shitty architecture and design that causes problems.
i used mysql for a long time and it was pretty stupid for me so i'd agree with dpy
anyway any idea for a solution to my problem?
Well most of the points in that image don't really mean much if you understand what's going on. For ex, many people using database don't even know what DDL is and if they did they would know it's not that big of an issue.
lol
if i wanted to increment a value in sql would be like SET count = count + 1, time = $1 WHERE id = $2?
Yeah
im not sure if it was because of putting () around count = count + 1, time = $1 last time it gave me an error
asyncpg.exceptions.PostgresSyntaxError: syntax error at or near "="```
this
Don't put it in brackets
Yeah
How do save all of the data from a SQLite database to a variable, then filter out to a certain match
i guess MySQL from versions 5.5 and below or something had some problems?
I dont know how, I was wondering if anyone knows
im waiting for Lufthansa to answer 😄
lol
Hes offline ):
Nvm figured it my self
Actually I need help again.
So I was able to get all of the information, but I want to update 1 of the int's by 1. Is that possible and if so how do I do it?
hi guys, i need some help with mongo db
pymongo.errors.ServerSelectionTimeoutError: No primary available for writes, Timeout: 30s, Topology Description: <TopologyDescription id: 6006f8ec04a73a5bd7ead835, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('cluster-shard-00-00.l3jul.mongodb.net', 27017) server_type: RSSecondary, rtt: 0.07734612872947946>, <ServerDescription ('cluster-shard-00-01.l3jul.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('connection closed')>, <ServerDescription ('cluster-shard-00-02.l3jul.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('connection closed')>]
this is a error i am getting
(i am using this with discord.py but the error seems to be about mongo)
One of the main things was they changed the default storage engine to innodb, and improved a bunch of things in later versions like atomic ddl statements.
oh ok , thanks :)
You can use the update statement https://www.w3schools.com/sql/sql_update.asp
so
Ok
oh nvm, its not py related
So would it be cursor.UPDATE?
Because it just says UPDATE
And that is invalid syntax
Cursor is an object that you can use to execute statements against the database. So it would be cursor.execute("update ... ")
Ok, but how would I recieve a value, like money made, then add 1 to that value?
It's better if you can provide your table structure and more detail of what you are trying to do. But generally if you want to update a columns value then you can do:
UPDATE table_name SET column_name = column_name + 1 WHERE some_condition
That would add 1 to the current value
Well I am making a xp system and I have 'id, xp, level'
And I am trying to make the xp go up 1
Also the table is called users
?
which one
wht do u guys think?
intro = input("""welcome to the government
seacret database please fill in your information.
if you wish to continue type next""")
if intro == "next":
ID = int(input("enter your ID"))
while intro != "next":
intro = input("""welcome to the government
seacret database please fill in your information.
if you wish to continue type next
NOTE:YOU ONLY HAVE 1 MORE TRY REMAINING """)
if intro == "next":
ID = int(input("enter your ID"))
x = input("to access please enter your password")
if x == "happyday":
print("access granted welcome comrade",ID)
elif x != "happyday":
print("access denied")
y = input("try again?1")
if y == "yes":
x = input("please enter your password")
elif y == "no":
print("throwing you out the system")
else:
print("enter either yes or no")
y = input("tryagain?")
if x == "happyday":
print("access granted")
while y == "no":
print("instaling hacking software onto your computer")
while x != "happyday":
x = input("please enter your password")
postgre? mysql?
sqlite3
YEs
Thank you got it to work
how do i use the motor module with mongo db ?
tutorial on their docs, comes with examples
hi i need advice on what i should to build my database in
it's all in csv's right now
Hey! I currently have an application on user's pcs that connects directly to my database. I want to know how can I prevent someone from just cracking my code and going into my database. What can I do? The client that they download only needs to insert. Is there a way I can make it so it can only insert to a certain collection and thats it? Or what can I do
Are Excel questions welcome in here? 😬 I know it's not a database..
can anyone help me connnect postgresql to flask?
newbie question: i just started today with sqlite3. i want to add a entry (idk how to call it tho.. i guess you can call it rows???). i want it to look something like this:
before:
last_name: Jass
after:
last_name: Jass
age: 27
I just started today so... yeah...................................................
with sqlite3 u usually have tables
kinda like an excel table in a sense
from ur example it seems that ur table needs an extra column to hold the age
u familar with sql syntax
a bit
i think sqlite3 might have like a editor thingy
where u can directly change ur tables without needing sql syntax
ALTER TABLE table_name
ADD COLUMN column_definition;
``` well this is from google
oh
so cursor.execute("ADD COLUMN ('age')") right?
or at least something like that?
uh u need to specifiy the table @ancient fog
like u need the ALTER TABLE and say what table u want to change
oops. ill appreciate if you show me how to do it
like im not familar with sqlite syntax but from google ur string has to be 'ALTER TABLE <ur_table_name> ADD COLUMN age;'
u didnt tell me what table those columns were from
so u have to fill that info in urself in where it says ur_table_name
is this ok?
cursor.execute(" ALTER TABLE crep ADD COLUMN 'age' ")
i forgot to put a datatype in the 'age' so imagine its 'age text'
i tihnk u dont need to encase ur column name in a string @ancient fog
unless thats a sqlite thing?
no thats a python thing i think
ok then
Yeah this one
Btw if you are using placeholders don't do that for tables and columns
They won't work
Any idea why sqlite3 is saying a certain column doesn't exist, despite it clearly existing? https://ram-ranch-really.rocks/8oTFsqB.png
vals = ", ".join(row)
keys = ", ".join(row.keys())
stmt = f"insert into `characters` ({keys}) values ({vals});"
conn.cursor().execute(stmt, list(row.values()))
print(stmt)
conn.commit()
conn.close()```
Ah never mind, used row not row.values() in line 1
Now I have to figure out how to sanitize this data 😄
Should we close our connections to postgres or keep it alive after work is done
I thought query commands have to upper case
INSERT INTO
not insert into
That's just convention
Depends on what you mean, if you will be using that connection again shortly don't close it. But if your script is going to terminate then you should close your connection
ah okay
im not sure why but my database isn't updating
await db.execute("""UPDATE votes SET voted = $1 WHERE id = $1""", "no", member.id)
idk why its not updating
oh okay wait
fuck
File "TESTER_BOT.py", line 42, in get_pre
c = await db.execute("SELECT prefix FROM guilds WHERE guild_id = (?)", (message.guild,))
File "C:\Python\lib\site-packages\aiosqlite\core.py", line 175, in execute
cursor = await self._execute(self._conn.execute, sql, parameters)
File "C:\Python\lib\site-packages\aiosqlite\core.py", line 122, in _execute
return await future
File "C:\Python\lib\site-packages\aiosqlite\core.py", line 98, in run
result = function()
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.
help
you're directly passing in the guild object
you want to be passing in the guild id - message.guild.id
I know I need a database for my discord bot, but idk how I’d make it so that my bot updates the database anytime a user interacts with the bot. I have the standard format:
CREATE TABLE info (id INTEGER PRIMARY KEY,
user_cash INTEGER,
user_token INTEGER);
INSERT INTO info (1, 3, 5);
INSERT INTO info (2, 6, 3);
INSERT INTO info (3, 10, 9);
INSERT INTO info (4, 2, 4);
INSERT INTO info (5, 7, 6);
SELECT * FROM info;```
How do I modify the query (once the table is made) to constantly update upon user interaction, and allow myself to view the “current” data at any point in a clean, readable manner?
Discord API in Python I get:
```[(1, 3, 5), (2, 6, 3), (3, 10, 9), (4, 2, 4), (5, 7, 6)]```
In an sql file, this:
```1|3|5
2|6|3
3|10|9
4|2|4
5|7|6```
...I’m confused
Neither display column names, which has me puzzled. How come the columns don’t show as a header for the table?
@solemn root To update values you can use the update statement. For example, UPDATE info SET user_cash = 100 WHERE user_token = 5.
And it doesn't show column names by default and instead just returns a collection of tuples.
If you want the column name or to access the result by column name then you can use the sqlite row class. https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.row_factory Either you make your own row_factory or use the already made Sqlite.Row class for this. The code in the link gives examples.
Hello is there any easy way in .fetchall() to change datetime.datime() object column to .isoformat()
other than enumerating and calling .iso format on every row
?
how can we use WHERE with two properties like
"SELECT names FROM shop WHERE items,currency = ?,?"```
in sqlite
you should be using AND/OR there depending on what you're trying to do
SELECT names FROM shop WHERE items = ? AND currency = ?
this will return names from shop where both conditions are met
if you use OR, it'll return names where either of the conditions are met
hey
hub = input("Enter \"HELP\" to view commands: ")
help = input("Commands: \n------------------------------\n\"LIST\": Views helplist of buyers and plans.\n------------------------------\n\"ADD\": Shows menu to add a user to the list.\n------------------------------\n\"REMOVE\": Shows menu to remove a user from the list.\n------------------------------\n\nInput: ")
db = ["User : Plan Expiry"]
if help == "ADD":
user = input("Enter buyer's username: ")
plan = input("Enter buyer's plan expiry: ")
print("Added " + user + " with " + plan + " expiry to the list.")
db.append(user + ":" + plan)
if help == "add":
user = input("Enter buyer's username: ")
plan = input("Enter buyer's plan expiry: ")
print("Added " + user + " with " + plan + " expiry to the list.")
db.append(user + ":" + plan)
if help == "Add":
user = input("Enter buyer's username: ")
plan = input("Enter buyer's plan expiry: ")
print("Added " + user +" with " + plan + " expiry to the list.")
db.append(user + " : " + plan)
if help == "LIST":
print(db)
elif help == "List":
print(db)
elif help == "list":
print(db)
if hub == "HELP":
print(help)
elif hub == "help":
print(help)
elif hub == "Help":
print(help)
else:
print("Invalid Syntax")
im making a tool
to manage some of my companys customers plans
for some reason the ADD and REMOVE isnt working
help pls <3
#conn = sqlite3.connect("mute.db")
#c = conn.cursor()
#c.execute("CREATE TABLE mute(guild_id INT, #userid INT)")
It says there no such table as mute
but the table is right there
help
do you actually commit said change
await conn.execute(sql, val)
await conn.commit()
yes
but the error is on the line above it
PLEASE PING ME
I think you do smth like Py INSERT INTO .... ON DUPLICATE KEY UPDATE .....
ok thanks!
I want to change the timezone setting in clearDB. But there's an error saying that we don't have enough permission. What should I do??
I want```
SET GLOBAL time_zone='Asia/Seoul';
But```
Error Code: 1227. Access denied; you need (at least one of) the SUPER privilege(s) for this operation```
plz help 😭 😭 😭 😭
What mean: Error binding parameter 1 - probably unsupported type.
In sqlite3
@sonic whale Linux?
Show the query
At creation or when i insert values @burnt turret ?
windows
Elevate your powershell @sonic whale
the query which raises this error
self.db.usersdb_cursor.execute(
'INSERT INTO infractions(user_id, user_name, moderator_id, moderator_name, reason, infraction_number) VALUES(?, ?, ?, ?, ?, ?)', (user.id, user, moderator.id, moderator, reason, infraction))
you're directly trying to insert the User object
which the database doesn't support
Damn.
By the name of the column I assume you want to insert user.name
and also moderator.name
There isn't much point storing that data though, just storing the IDs should be enough
@burnt turret sqlite3.InterfaceError: Error binding parameter 3 - probably unsupported type.
and when you need their names there are discordpy functions to get the Member object back using the ID
Whut?
that's odd, can you show the query now?
INTO infractions(user_id, user_name, moderator_id, moderator_name, reason, infraction_number) VALUES(?, ?, ?, ?, ?, ?)', (user.id, user.name, moderator.id, moderator.name, reason, infraction))
huh. can you show the code where you define user and moderator?
@commands.command(name='warn', enabled=True)
async def warn(self, ctx, user: discord.Member, *, reason=None):
moderator = ctx.author
self.db.usersdb_cursor.execute(
'SELECT infraction_number FROM infractions WHERE user_id == {0}'.format(user.id))
await ctx.send(self.db.usersdb_cursor.fetchall())
infraction = 0
if reason is None:
reason = 'No reason provided.'
else:
pass
self.db.usersdb_cursor.execute(
'INSERT INTO infractions(user_id, user_name, moderator_id, moderator_name, reason, infraction_number) VALUES(?, ?, ?, ?, ?, ?)', (user.id, user.name, moderator.id, moderator.name, reason, infraction))
self.db.usersdb.commit()
await ctx.send(f'{moderator} + {moderator.id} + {user} + {user.id} + {reason}')
that's odd; i don't see why that shouldn't work
There isn't much point storing that data though, just storing the IDs should be enough
and when you need their names there are discordpy functions to get the Member object back using the ID
this is better IMO
avoid storing unnecessary data
after all, the user and moderators names could change later on, making your data inaccurate
also unrelated to the question but:
- don't use f-strings/str.format() in queries - #databases message
- for a discord bot you should be using aiosqlite, as sqlite is blocking
mysql> SET GLOBAL event_scheduler = ON;
ERROR 1227 (42000): Access denied; you need (at least one of) the SUPER privilege(s) for this operation
In clearDB. What should I do?
I use heroku and use add-on clearDB.
ClearDB doesn't give Access Permission. Oh, damn it
I don't understand second point, why did you say that? Can you explain me?
Your discord bot is asynchronous, while sqlite is synchronous
so everytime you try doing something with the database, it'll block execution
and your bot won't respond for that time
using aiosqlite module will make your database interaction asynchronous as well
so that your bot won't freeze
aiosqlite is a different module to interact with the same db, you'll just have to change some code
Do you know how can i add +1 to infraction_number?
I do this, but i don't know how to add value.
self.db.usersdb_cursor.execute(
'SELECT infraction_number FROM infractions WHERE user_id == {0}'.format(user.id))
await ctx.send(self.db.usersdb_cursor.fetchall())
UPDATE infractions SET infraction_number = infraction_number + 1 WHERE user_id = <>
```something like this
Oh i see! Yes thx ;)
Anyone have experience using ssis and python? Pls ping, just looking for beginner tips to jumpstart myself with
can someone join me in help-aluminum. I have an issue with Django communicating to a postgresql database, i dont know why
'Hello to all : I need help to figure a correct syntax issue with mysql.connector...
I would like to add a list of dictionaries into a table. All the dictionaries have the same keys but different values.
The names of the columns of the table have the same name like the keys.
dicolist = [{'code': 'val1', 'name' : 'val2', 'description': 'val3'}, {'code': 'val10', 'name' : 'val20', 'description': 'val30'}, {'code': 'val11', 'name' : 'val12', 'description': 'val13'}]
query = "INSERT INTO product (code, name, description) VALUES ('%s','%s','%s')" % ?????
self.cursor.execute(query)
self.connect.commit()```
I don't know how to write the values of the query...
Can somebody help me ?
Any good resources that anyone is aware of for database implementation with discord.py?
In what context?
If you just want to implement, say, asyncpg with discord.py, here's an example:
async def run():
credentials = {"user": "username", "password": "", "database": "database_name", "host": "127.0.0.1", "port": "5432"}
async with asyncpg.create_pool(**credentials) as database:
bot = YourBot(command_prefix="!", database=database)
for extension in EXTENSIONS:
bot.load_extension(extension)
await bot.start("token")
loop = asyncio.get_event_loop()
loop.run_until_complete(run())
And then, in your bot class, you can:
I have little database experience, I do have a pretty cool bot that I’ve developed. I’d like to be able to use it across multiple servers with server specific settings. So I’m looking for something to reference that will maybe point me in the right direction on how a database is generally used with discord.py
class YourBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.database = kwargs["database"]
@commands.command()
async def example(self, ctx):
await self.database.fetchrow("query")
These are some modified examples from my bot
Using asyncpg
@lost pendant
No problem :D
I can't connect to my database for some reason
does the user ur using have the right password and permissions @fiery bone
@smoky pendant Yes, I've tried even creating a new user with all privilages
It still says
(10061 No connection could be made because the target machine actively refused it)
I've allowed the port through windows firewall
When I disables windows firewall I got a new error message
(10060 A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond)
@fiery bone - if the connection is being actively refused the server may not allow remote connections - check your pg_hba config file
that is a postgres answer - darn - but sounds like remote connections are not allowed on the server itself
well it is a vps
when I installed mysql I did set it to allow remote connections I'm pretty sure
if you run netstat do you see the port opened for localhost or 0.0.0.0 - localhost(127.0.0.1) only allows local connections while 0.0.0.0 will allow external connections
it's localhost
check your config file and make any chances necessary to allow remote access
yay new error!!
now it says my specific host is not allowed to connect
I just have to whitelist it
Any reason not to think that means exactly what it says? It expected a date or a datetime, and instead you passed a timedelta.
WOOHOO!! @torn sphinx you are a legend!!
glad I could help
And which of those lines does the traceback say the error is on?
The traceback is telling you what's wrong.
It's telling you which line is wrong, and what's wrong on it.
Yes but why wouldn't my timedelta.Timedelta work now like I don't get it?
Which line is the problem on?
ok - so you're trying to pass t2 into the database as a parameter, and t2 is a Timedelta, and the database doesn't want a Timedelta, it wants a date or a datetime
My column is TIMESTAMP WITHOUT TIME ZONE though.
Should I do it BIGINT or INTEGER?
someone know how to make pandas work with pygal?
What is the column supposed to store?
you can't add two timestamps together
"what's now plus tomorrow" is nonsense
if it's supposed to store a duration, or the difference between two times, then you're looking for an INTERVAL column.
if it's supposed to store a timestamp, then TIMESTAMP WITHOUT TIME ZONE is the right type to use, but you need to pass a date or a datetime
its for me? . _.
so how and what should i store?
no, none of that was for you. I don't know pandas.
oh ok
I still don't understand what you're trying to do, so I can't answer that.
I have seen your code, and don't understand.
when u do !on it stores the time
and when u do !off
it tells u how much timed passed
not i want a total !time for how many times the person has done the commands
so how much total time has elapsed between !on and !off commands? If they do a !on at time 0 and a !off at time 3 and a !on at time 12 and a !off at time 15, you want 6?
then TIMESTAMP WITHOUT TIME ZONE is entirely the wrong type, and you want an INTERVAL column instead.
that represents a duration.
TIMESTAMP represents a day and time. INTERVAL represents a number of seconds.
yes but i dont have a type lf seconds do i?
i got like month/day/year minutes/seconds/milliseconds
no, you don't.
you had that, but then you subtracted it from another month/day/year minutes/seconds/milliseconds, and the difference between two of those is a number of seconds.
That's what this is doing: ```py
t2 = timedelta.Timedelta(ctx.message.created_at - tm['time'])
oh u right so what should i store in my bottom queries then?
the total amount of time that something has been on is a duration, which means you want an INTERVAL column.
so t2.total_seconds() to get hours and minutes?
INTERVAL columns want a datetime.timedelta as their value.
there's no need to pull hours and minutes out of it.
so you're trying to subscript None on this line: ```py
t2 = timedelta.Timedelta(ctx.message.created_at - tm['time'])
subscripting is using []
which tells me that tm is None
Doesnt seem to work @radiant elbow should i just store the seconds?
t2.total_seconds() as INTERVAL/
where did tm come from? Wherever you got tm from, it gave you a None.
it probably came from a column whose value was null
it is not none though @radiant elbow
yes, it is. print it.
Python's error messages aren't lying to you.
that looks reasonable.
no errors at all
is this unrelated to the last error you showed?
nope
last error is just some "python or postgres" unkown error
but code works
it just throws an error
no reason 😛
the last exception you showed was at:
File "C:/Users/NtinosThanos/PycharmProjects/Greek Mafia Roleplay Bot/Paradox Roleplay.py", line 138, in off
t2 = timedelta.Timedelta(ctx.message.created_at - tm['time'])
TypeError: 'NoneType' object is not subscriptable
I don't see that line in the latest thing you pasted.
yes that error
is fixed
i mean i still get the error but its working
its from another code
now the code up there doesnt work and i think its some problem with how i get things from db
"doesn't work" how?
like is the query right?
no, the query is not right. You're using group by, which means that all of the columns that you select must either be included in the group by clause or be the result of aggregate functions. member_id is not.
I don't know what timedelta.Timedelta is - why aren't you using datetime.timedelta?
@radiant elbow wait so what i need to change in the query
so i get like the time and member_id from someone but it goes from most time to lowest
what is the query supposed to be doing?
if u get me
then you don't want a group by at all.
SELECT time, member_id AS NUM FROM paradoxtotalactivity ORDER BY TIME DESC
i dont need AS NUM too right? @radiant elbow
probably not.
that would make it so you access the column using "num" instead of "member_id" in your Python code.
Does anyone know how to delete a table from sqlite
c = cursor
i want to delete memes coloum
pls help me
Do you want to drop the table or the column?
coloum
sqlite doesn't support dropping columns. See https://www.sqlitetutorial.net/sqlite-alter-table/
Sure, that's just an UPDATE statement.
quick question, ^ comfybot=> SELECT num_votes FROM INFORMATION_SCHEMA.COLUMNS; ERROR: column "num_votes" does not exist LINE 1: SELECT num_votes FROM INFORMATION_SCHEMA.COLUMNS;
user_id | num_votes
--------------------+-----------
713979128969429012 |
(1 row)
``` why do i get a column doesnt exist and when i try to select from num_votes in asyncpg i get a undefined column even though the column is there?
solved that, didnt fully understand info.schema.columns
hi i using sqlite3 i want to create a login data base with two coloms user and password
what will sql return when the WHERE requirment is not met?
like where username = "johan" and password = "123"
what will it return if that username and password is not there in the table?
what method are you using ?
fetchone() returns None, fetchall() returns an empty list etc.
this is documented
oh ok thanks a lot
can you pls send me the link
thx
You'll need to put some code into your login function, at least a temporary pass statement
Otherwise it'll give you an (indent) error
😆
hey I'm new to databases
what am I doing wrong here?
I thought that on line 2 is where you specify which columns to change and in VALUES you specify the values to change
I am pretty sure you need to use ' instead of "
doesn't it depend on the database being used? postgres uses ' but i think mysql doesn't mind either iirc
is there anyone that uses replit
else:
bal = collection.find(user_ide)
async for i in bal:
bal_actual = i["balance"]
bal_updated = round(bal_actual + suma_daily, 2)
await collection.update_one({"_id":user_id}, {"$set":{"balance":bal_updated}}, upsert=True)
await ctx.send(f"**Ai primit {suma_daily} :currency: din daily!**")
TypeError: object AsyncIOMotorCursor can't be used in 'await' expression
TypeError: object AsyncIOMotorCursor can't be used in 'await' expression```
what
this isn't what you have in your code tho 
either ways, try
bal = await collection.find(user_ide).to_list(length=None)
actually you don't need the find query
you can directly update, but instead of using $set operator, you'd use $inc
inc stands for increment
so it'll add the value you pass to it to the existing value
That solved my issue, thanks
What a pythonist should know about DBs? I'm still managing with the concept of selects, joins, where and aggregations, but I feel my foundations are shakey. What are your favorite SQL exercise websites? Preferably Oracle.
In the mute command for my discord bot I have this: append_member_to_db(member_name=member, member_id=member.id) (i am importing this above), but when I use that command I get this error: InterfaceError: Error binding parameter 1 - probably unsupported type.what do they mean by probably unsupported type.?. Thank you
you need to show the query, but #databases message i'm guessing something like this is what is going wrong for you too
@simple moth Go with sqlzoo (https://sqlzoo.net/). Covers pretty much everything from basic joins to more fancy stuff
Thanks! I'm currently going with livesql.oracle.com, but sqlzoo seems nice too.
Vanilla SQL is not too different from Oracle but the main concepts are there
Ya, looks like I have the same problem, what can I do to fix it?
some1 here understand pandas librarie?
@burnt turret what should I do?. (sorry for the ping)
@austere portal your error says you are giving wrong type so then give the correct type
show the query
if your column is supposed to be storing IDs, use member.id in your query instead of member @austere portal
Thanks, I just specified the arg type: append_member_to_db(member_name=str(member_username), member_id=int(member_id))
if this is a discord bot there isn't much point storing usernames though
the username can change
the ID won't
- if you have the ID, you can get the username and other details at anytime
is there a big difference between aiosqlite and sqlite?
aiosqlite is asynchronous, sqlite is synchronous
meaning if you use sqlite, the database calls will be blocking
and your bot will freeze for the time that it is interacting with the database @austere portal
if anyone knows plz ping #databases message 😬
What would be the best api to get a bunch of images of that precise thing. I know that there is a google images api, but google images is not as relevant as I want it to be. I am trying to make a command that pulls an image of that certain thing.
async for i2 in result2:
if i2 == None:
ctx.send()
How can i do to send something if find returns nothing in mongo
with "None" doesn't work
nvm
forgot that count_documents exists
any sql debugger got a set of code for yaal
Hello, I'm looking for a phytoneer or pythonistas that could give me free tutoring. Covid has changed the way we look at the world and therefore I am learning programming to make a career change. Your efforts will not go to waste and I'm highly motivated in learning and studying which will make it easier for you to teach me.
The benefits you will get is learning how to teach and tutor with a highly willing, understanding, and adaptable student. If you're one of those rare people that values knowledge and wisdom then you shall receive it in abundance from me in return for your knowledge.
Please contact me trough PM.
I'm trying to use postgresql in pycharm, I've connected it but nothing is showing up under schemas
is there a way i can make an empty table in sqlite3?
guys how can i check tables in database (pg)
how do u plot a roc curve for linear regression?
quite sure when u create a table its empty
i mean empty in terms of entries
but u will still have the columns that u defined it to have
r u signed in as root
bc in mysql u cant see tables that u dont have permissions for
sorry bro forgot to say It loooks like its working now
well thats good
How do I navigate around integrity errors? I feel like I need to have logic saying "if table doesn't exist, create the table, else, update it" but how? I'm not too familiar with databases.
It happens on the line where I insert the first row (when running the code more than once)
that prob most means there is like a column that must be unique like primary key and u inserted sth that was a repeat
I want lines 6-20 to run on first creation of the table, but if the table exists, run line 22-23 (plus other Update logic in the future)
Also, Autoincrement doesn't seem to work how it's supposed to. (if I remove the manual incrementing I declare, it complains about not having enough values)
if ur auto incrementing i dont think u need to manually insert a PK
that doesnt look right
u dont pass the literal id into values
its like usually INSERT INTO tinker (user_cash, user_token) VALUES (3,5);
How do I check if a user has a value in JSON? as there can't be duplicates
{
"692380305805541430": 123,
"786098988755320852": 123
}
``` I need to avoid this (they both cant have 123)
ping if u can help
Thanks! It works now 🙂 Just have to figure out how to prevent row creation every time the code runs unless specific conditions are met.
:l
one way is to subquery
I have to check if discord users have interacted with the bot (which is what I need the database for) before, and only create a new set of rows specific to that user, on the first bot command that user sends.
bump
yeah u will have to do a search than check then insert
So, only create a database entry on first user --> bot interaction, then update their entry on every future bot command they send
yeah that seems to work
bump
@inland remnant parse the JSON and create a counter of values
File "/home/admin/.local/lib/python3.7/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/admin/testcomf/cogs/votes.py", line 36, in votes
res = await con.fetch('SELECT num_votes FROM votes WHERE user_id = $1', user.id)
File "/home/admin/.local/lib/python3.7/site-packages/asyncpg/connection.py", line 443, in fetch
return await self._execute(query, args, 0, timeout)
File "/home/admin/.local/lib/python3.7/site-packages/asyncpg/connection.py", line 1446, in _execute
query, args, limit, timeout, return_status=return_status)
File "/home/admin/.local/lib/python3.7/site-packages/asyncpg/connection.py", line 1454, in __execute
return await self._do_execute(query, executor, timeout)
File "/home/admin/.local/lib/python3.7/site-packages/asyncpg/connection.py", line 1466, in _do_execute
stmt = await self._get_statement(query, None)
File "/home/admin/.local/lib/python3.7/site-packages/asyncpg/connection.py", line 351, in _get_statement
statement = await self._protocol.prepare(stmt_name, query, timeout)
File "asyncpg/protocol/protocol.pyx", line 163, in prepare
asyncpg.exceptions.UndefinedColumnError: column "num_votes" does not exist
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/admin/.local/lib/python3.7/site-packages/discord/ext/commands/bot.py", line 902, in invoke
await ctx.command.invoke(ctx)
File "/home/admin/.local/lib/python3.7/site-packages/discord/ext/commands/core.py", line 864, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/admin/.local/lib/python3.7/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: UndefinedColumnError: column "num_votes" does not exist```
im 100 hundred percent sure im in the right db
;
user_id | num_votes
--------------------+-----------
713979128969429012 | 2
(1 row)
async def votes(self, ctx, user: typing.Optional[discord.Member]):
if user is None:
user = ctx.author
else:
user = user
async with self.bot.pg_con.acquire() as con:
res = await con.fetch('SELECT num_votes FROM votes WHERE user_id = $1', user.id)
await ctx.send(f'{user.mention} has {res[0][0]} votes')
``` the code im using to get that error
well just to completely eliminate the possibility that u connected to the wrong db what db do u specify when u first establish the connection
async def create_db_pool():
bot.pg_con = await asyncpg.create_pool(database='comfybot', user='admin', password='password')
bot.loop.create_task(create_db_pool())
i even made a whole new table and added a different name for the column but it gave me the same thing
what if u tried SELECT confybot.num_votes FROM votes WHERE user_id = value
i feel technically u shouldnt if u connected to right database
have u tried running the query from a terminal or sth
Hey, I've been using the sqlite3 module for a bit and am now using threads, which is not possible without using locks to safely access the database.
I want to stick with core modules, but I'll switch to SQLAlchemy if it lets me keep most of the same commands the same while letting me use threads.
Anyone know about switching from sqlite3 to sqlalchemy? Do I have to do the whole ORM song and dance or can I just do execute(query) exactly like before?
well ive used sqlalchemy when i followed a few tutorials and its really similar to how django does stuff
so basically u define some models and the models get mapped to database tables
also im quite sure sqlite3 has an async lib
to deal with transactions that are concurrent
How can I access my database from my main file if I have all my database create, replace, update, delete code in a separate file? I only want to use my database when I need to, so making calls to it seems more effective than implementing redundant code.
import it?
I import the module, then call the module, but that’s where I get an error: ‘module’ object not callable
how can I call all the code inside the module since I can't call the module then?
its like module.function if u do import module
yeah i think so too
but the thing is when u connect to a specific database u shouldnt need to specify the database in the query
It worked! Thanks 🙂
great
hi im new to Django what will happen if i run Django without a virtual environment?
!warn 605807288489476131 Do not post the same question many times across the server. If you need help, please use our help system #❓|how-to-get-help
:incoming_envelope: :ok_hand: applied warning to @alpine gazelle.
how can i use sqlite3 to check if a value exists in a certain column of a table
Guys how can i check that a mysql Delete query was successfull?
Hi, I am new to coding and am currently working on a project with Python. Has anyone here ever deployed Python script on AWS lambda?
Hi, I'm trying to make a field in my Django model derived from another model. For example, I have integer fields in my profile model titled followers and following, and I'd like to get those values from another model by aggregating (count). This other model stores the relationship of users; i.e. who is following and being followed. How am I supposed to go about and get the count of followers and following of each respective user? Really appreciate the help, I'm just new to the world of Django.
Hello, I have a sql error, I want to insert the nickname of a person in lowercase but with special characters, mysql does not accept it
pseudo= "".join(char for char in ctx.author.name if ord(char) < 128)
pseudo = pseudo.replace(" ", "").lower()
print(pseudo)
cursor.execute(f"SELECT fullname, id FROM compte WHERE fullname='{pseudo}'")```
error:
```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'x>'' at line 1```
thats a real bad idea
you should NEVER be using string formatting with query parameters
we have a pinned message here explaining why you shouldnt - #databases message
How do I delete a column from a table?
syntax varies slightly between databases but i think it should be something like
ALTER TABLE tablename DROP COLUMN columname
at least i think that's what it is in postgres
Thanks, but how do I delete a column by the member id without deleting it by the column name
Thanks, but will I need to make any big changes to the current code?
what do you mean?
do you want to delete a row?
yes a row
that's done with a DELETE statement
DELETE FROM tablename WHERE member_id = <some member id>
Thank you 🙂
will I need to make any big changes to my code when I switch from sqlite to aiosqlite
i haven't used either but i don't imagine there's gonna be much difference other than adding awaits before queries
i may be wrong though
Ok, thanks again
i have this error ```cursor.execute("SELECT fullname, id FROM compte WHERE fullname=?", (pseudo,))
File "/home/pi/.local/lib/python3.7/site-packages/mysql/connector/cursor.py", line 543, in execute
"Not all parameters were used in the SQL statement")
mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/pi/.local/lib/python3.7/site-packages/discord/ext/commands/bot.py", line 902, in invoke
await ctx.command.invoke(ctx)
File "/home/pi/.local/lib/python3.7/site-packages/discord/ext/commands/core.py", line 864, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/pi/.local/lib/python3.7/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: ProgrammingError: Not all parameters were used in the SQL statement```
in
cursor.execute("SELECT fullname, id FROM compte WHERE fullname=?", (pseudo,))```
Hi, I am trying to change my function which is using sqlite to aiosqlite, this is my code:
async def append_muted_member_to_db(member_name, member_id):
conn = await aiosqlite3.connect("muted_members_db.sqlite3")
local_time = localtime()
time_format = "%Y %H:%M:%S"
current_time = strftime(time_format, local_time)
command = "INSERT INTO Muted_Members VALUES(?, ?, ?)"
await conn.execute(command, (current_time, member_name, member_id))
await conn.commit()
await conn.close()
and I am using that function like this await append_muted_member_to_db(member_name=str(member), member_id=int(member.id)), but I get this error: Command raised an exception: OperationalError: database is locked, What does it mean by database is locked?. Thank you
how do i select a whole row's data when a the rows value = something
lets say i have a row
Username Password Salt
User1 Pass1 Salt1
how can i get that rows data when salt = Salt1 lets say
so, to get everything from a row, you'd specify * in the place you usually write the columns you want, and then you use a WHERE clause to check the condition
SELECT * FROM tablename WHERE salt = "salt1";
hmmm, whats the return value type, list?
that depends on what method of your db driver you use
fetch returns a list of tuples where each tuple is a row,
fetchrow returns the single tuple
or something along those lines
actually theres no point asking that since im not even using python but this is the only server with a databases chat lol
thanks
conn = await aiosqlite3.connect("db.sqlite3"), this code isn't doing anything?
shouldn't it make a file named db.sqlite3?.
Can anyone explain what they mean by
Select a.item_Type
Input Table
ItemType(ItemTypeCode,ItemTypeName,ItemCategoryCode,ItemID)
ItemCategory(ItemCategoryCode,ItemCategoryName,ItemID*)
SQL Query
Select a.Item_Type,a.ItemTypeName,b.ItemCategoryName
from ItemType a ,ItemCategory b
where a.ItemCategoryCode = b.ItemCategoryCode
This statement suppose to display names of all item types with their category names, is it correct?
.
are you using a connection pool?
oh i seem to have misunderstood the question 😅 i'm sorry, i don't know the answer to this
um if passwords are stored in the form of digests and hash function is not reversible, how are passwords still "hacked"?
well its hashed when stored but if ur password itself is weak
Database leaks
and ppl can just guess it
oh
which have a bunch of pre hashed passwords that are known
or just brute force
any password less than 8 character encrypted in MD5 can now be brute forced in a pretty arbitrary amount of time aswell so things like outdated system leaks give even more commonly used passwords etc...
Rainbows tables basically trade Disk space for CPU time
ah I see
so these things are often massive containing billions of passwords pre-cracked
Which is why salting your hashed passwords with a unique per-user salt is important
gotcha :) thx
bLOcK CHaIN
If I wanted to make this game and I wanted all but 2 values to start at 0 what could I do to accomplish that (sqlite3 btw)
what should i name my database file?
test.db
test.sqlite
test.mdb
any ideas
lol its there a reccomend one for SQLite
does anyone know how i can use INSERT to add both variables and strings to a table
in sqlite
rn im getting sqlite3.OperationalError: near ".": syntax error
filename.db is usually used for databases
db or sqlite
I made a DB in DB Browser, I added data to it with my python script, I can see the data in the table being added. When I try to draw the data from the table it returns error
c.execute('SELECT * FROM questions_agree')
sqlite3.OperationalError: no such table: questions_agree
First check if you made a typo when you did sqlite3.connect then check if you made a typo in dB browser when creating the table
And also check if you saved/committed your changes
import sqlite3
conn = sqlite3.connect('employee.db')
c = conn.cursor()
c.execute('SELECT * FROM questions_agree')
print(c.fetchone())```
I can see the changes in the db when I use DB Browser, but my DB Browser acts a little strangely, I used it to create the table so maybe it some how did something weird I'm not sure.
You should be using fetchall() when using SELECT *
Like my scraper is saving to the db so I don't see how the table doesn't exist or I don't know how to select it
Have you checked if youve committed your changes from the browser
from the browser?
my code has commit in it
I think my db browser is stupid and i dont know why, even since i install it it crashes if i use drop down menu to change a column type
so maybe because i made db in there
is there another program to try than db browser
You could use it from the command line
i made this table and db in db browser where as the other one i had working i created myself with code so thats the only difference i can see
so much nicer to have function gui than code everything in python lol
I've had to live without a GUI because the stupid db browser crashes when I do anything
oh nice you have the same problem
Not nice at all acc 
i will try manually coding the entire data and then fetching new data and seeing if i can get it to work lol
I have this User Class
class User(db.Model, UserMixin):
And this karma value in it
karma = db.Column(db.Integer, nullable =False, default = 0)
I would like to display the users based on who has the greatest karma
topUsers = User.query(User).order_by(User.karma)
somthing like this where i quesry my database and order by karma. howewer this isnt working. Could anyone please help me please?
This is Using SQL alchemy in python3 flask
I've never really done anything to do with your specific issue, I've only really done things such as student databases and currency systems. I haven't done any sort of ordering by karma so I can't really help with that sorry
Thank you for your help
Also, I don't mind being pinged, do it as much as you like!
no this SQL alchemy
Oh, misunderstood, also never used that lol
lol
Hi there, from this code, ```py
results=collection.find({})
for r in results:
print(r)
I just wanted to find "skins" under this ```{'_id': ObjectId('600b12179d28138ad857f261'), 'Skin': 'BattleByte', 'source': 5}
{'_id': ObjectId('600b1265e54dd0c00ebf6482'), 'Skin': 'BattleByte', 'source': 5}
{'_id': ObjectId('600b1265e54dd0c00ebf6483'), 'Skin': 'BattleByte', 'source': 5}``` what can I do?
Like I just wanted the value of the key "skin"
Oh and it is pymongo
Mongo DB
Does mongodb have a limited amout of use hours per month?
I need to store like a single file with a bunch of numbers etc. will that use to much storage @smoky pendant
is the json format still used in mysql?
i kinda just decided to switch from json files to sql
and im wondering that
i think its still there
but ive read ppl say to avoid that to improve search speed
but ive never used it
like if i think i have destructured data i just use mongo
whats with mongo
yeah
well json u have to load the entire file
.json
and if its big its gonna take some time
and with mongo?
well technically its not loaded for each individual search
and is it easier to access data too?
and i think mongo supports searching for different parameters
like you dont have to do data[example][example][example]
if you dont have to do that each time then im changing my whole code just to adapt it to either sql or mongo
it uses sth called collections
tbh im not entirely sure
i will be updating lots of data with my discord bot
thats why im asking
o ok
well from what you just said
sounds interesting
thanks for your time
ill look more into dbs
yeah ive mostly been using sql
o thats why
but apparently ive been introduced to mongo
so what do you recommend? sql or mongo?
or at least something im working on is already using mongo bc of other ppl
just to start with
i mean u choose based on how ur data is shaped
its just dictionaries
i mean if its structured sql is nice
if its not really structured mongo or some other non relational db works
wdym by structured
like it follows an order?
it has definative fields
o ok
sure its ok
its different
im gonna watch some tutorials tomorrow because i have been learning discord.py the whole day
thanks again
.find takes two arguments, the first is a filter (mongo will only return those documents where the condition specified in the filter is met) and the second is where you specify what fields you want returned.
In your case when you want every field, you'll leave the first dict empty like you have, and in the second dict you'll specify you only want "skin", like
collection.find({}, {"skin":1, "_id":0, "source":0})
Saying skin: 1 tells mongo that you want that field, and the rest: 0 tells mongo you don't want those
When does limit take place?
I know it's at end but what if limit is less than how many rows match where clause? Does it stop after it gets its limit or still applies where to all?
then you only get the number of rows you asked for
I know what it does
I am asking if it stops searching as soon as limit had been reached or if it applies limit at the end result set
"SELECT * FROM server_ranks WHERE server_id=? id=?"
how can i run this
i want to put 2 parms
sqlite3.OperationalError: near "id": syntax error
it keeps giving this error
#databases message similar answer
thank you
How can I write a SQL query which checks if a value must be equal to X and another value Y has to be in any of 3 columns?
Hi i'm using sqlite and in one of my tables, i did PRIMARY KEY to a column called user_id but instead of that i want it to be not just unique directly but has a limit
Like right now if i try to insert the same user_id, it gives unique error right but i want it t o be like user_id is unique after 5 entry
It is like counting
How can i do this in sqlite?
Are there something like
PRIMARY KEY (user_id, limit=5) or (user_id, count=5)
I have the following code:
@commands.Cog.listener()
async def on_message(self, message):
if message.author == self.bot.user:
return
keywords = message.content.lower().split()
data = await self.db.fetch('SELECT Highlights.keyword, HighlightSubs.user_id FROM Highlights INNER JOIN HighlightSubs ON Highlights.id=HighlightSubs.keyword_id WHERE Highlights.keyword = ANY($1)', keywords)
tasks = []
for record in data:
embed = discord.Embed(title='Highlight!', description=f'[{record["keyword"]}]({message.jump_url})', color=self.bot.color)
embed.set_author(name=message.author.name, icon_url=str(message.author.avatar_url))
user = self.bot.get_user(record['user_id'])
if user != message.author:
tasks.append(user.send(embed=embed))
for task in tasks:
self.bot.loop.create_task(task)
``` and I get the following error: https://paste.pythondiscord.com/wukikulalu.sql
I'm using asyncpg
the full code for this Cog is available at https://paste.pythondiscord.com/upibukujan.py
do you need to specify NULL/NOT NULL when you have default as a constraint?
Mate, @burnt turret for py results=collection.find({"_id":2}, {"skin":1,"_id":0}) for r in results: print(r)why is it showing like this?{'skin': 'Nothing'}I want it to just print "nothing"
this is because mongodb documents are in JSON format - meaning they're dictionaries
i.e key: value pairs
Oh. I see.
if you want just the nothing part, you'd use it like any dictionary in python
Yes so I have to do r["skin"]
Anyone know if gkrou or the Lufthansa persons are in this server still?
yep 👍
THank you my guy
LP is still around, i'd seen him yesterday-ish i think
I've been waiting for reply to my questions for like days now no one replies. 🥺
Yeah I ask yesterday also
oh is it this one? i didn't answer because i didn't have a good enough answer haha
but reading it, wouldn't you just use OR a bunch of times?
That is one but I had also a few others
or does the any 3 columns mean it could be from any columns in the table
oh right 👍
Let me get the other
This
And thus also 😬
i don't know enough about DBs to answer either haha I'm sorry
Hmm ok but thanks anyways
I am having a problem in here
I have to make a user signup code where every user inputs one username (kinda like reddit) but it is not happening
does anyone know winreg
are the contents for requirements.txt okay?
PyNaCl==1.3.0
pymongo
dnspython==1.16.0
async-timeout==3.0.1```
for these headers
```import discord
import datetime
from discord.ext import commands, tasks
from itertools import cycle
import pymongo
from pymongo import MongoClient```
anyone here experience with MongoDB?
ask your question and someone will answer if they can
Alright
best database to use for a discord bot?
aight
thx
might if i dm? @crude shard
Um please keep it here
ok
Because I learnt what I know from people here.
So i am working on a discord bot and i am using data base to store information.
But i am wondering if you could modify information in the cluster using command on discord..
MongoDB is a simple and easy to use database. This tutorial will show you how to use MongoDB with python and the python module pymongo. Pymongo is the offical MongoDB API that allows for you to easily perfor mdatabse operations.
Please Note: This is simply the basics of MongoDB in python, it is meant to get you started and give you an introduct...
wait what whats with mongodb
they give free hosting
but i can host it by myself right?
They give database. Do you need hosting or database?
I can host it so just the database
they give a limited amount of space
tho
and i cant find any tutorial to host it locally
What are you hosting?
dont you need to host the database yourself so that you dont need to pay?
im getting confused lol
You can host for free on heroku
kinda new to this sorry
No just tell me what are you developing
o ok
i just want to save user data and bot data in a database
from a discord bot
save, update and read
i gues
s
thing is i dont really understand databases that much and people just told me that its an upgraded json
that doesnt corrupt and its easier to access
ok ok
at the moment, saves fictional character details and contains a gallery of pictures from each of them
and you can access the galleries
and those details
just that
but im planning to add more
inventory system, leveling system, minigames, currency, etc
thats basically it
Yes so use mongo db for storing the details and heroku to host it for free 24/7
will i ever run out of space
imo you're better off with a relational DB like postgresql/mysql - sure mongodb is easy to set up and all but rarely is the data for you bot unstructured
they're both SQL databases
but
thing is
when i searched for sql
i got like 5 results
mysql
sqllite
anasql
SQL is the query language
oh ok
there are many SQL databases
basically relational databases (the ones which use SQL) store data in tables
in mongodb there is no structure as such, it's just JSON
this lack of structure can be useful, but most use cases can be covered with relational databases
so i should just use mysql?
well that's your decision
and yes you can install mongodb and run it locally too
same applies for mysql, or postgres or almost anything else
how are you hosting your bot?
my pc
you can just search for how to install mysql
it isn't a complicated process, there's an installer and you just follow the steps
is there a ui to manage data easier?
for mysql there's something called mysql workbench i think
ooo
it'll still be easier to do queries though for more complex stuff, but yes workbench is an option
i don't think you should be posting memes around here but if you're being serious about that - #databases message
the link just explains why you shouldn't be using f-strings for queries

i mean that depends entirely on your use case and whether you are accepting user input from anywhere
true
you can also use docker for that
how would one structure an account managing projects DB
my system:
one login table which stores login details
a table for each user with all their accounts
a system that was suggested
one login table which stores login details
one table for every users details
?
thanks
one table for every user seems better
making a table for each user is rather wasteful
but surely it would be faster with a table for each user since you only need to access one table rather then a table with loads of irrelavent data of other users
@burnt turret
dont think so
joins and foreign keys would be really hard to emulate with such approach
yep
ah that makes sense thank you
i just thought it would be a more structured approach
parameterised queries also have other benefit like how parameters are binded, and also most orms use this as well
@red robin you'd use ORDER BY in your query, or use an ORM (which is my preferred approach)
ORDER BY also takes ASC or DESC to sort ascending or descending. e.g. ORDER BY high_score DESC (high to low)
assuming high_score is an integer field; if it's text you'll have different ordering
@celest zodiac id want to be like this [(1, 871812), (4, 148898), (28, 6233), (13, 3266), (27, 2000), (2, 0), (3, 0), (5, 0), (6, 0), (7, 0), (8, 0), (9, 0), (10, 0), (11, 0), (12, 0), (14, 0), (15, 0), (16, 0), (17, 0), (18, 0), (19, 0), (20, 0), (21, 0), (22, 0), (23, 0), (24, 0), (25, 0), (26, 0)]without , and ' ([
then you'd sort by whatever the second column is, descending
and without the oid
the commas and brackets are just the formatting Python applies when you print the results to the console
do not select oid than
What does database is locked mean in sqlite?
ok thx
i'm quite sure it means that your not allowed to complete your transaction bc someone else is still completing their transaction.
It usually means your application is open twice, or you have a database editor with the database file open for writing at the same time your application is trying to open it for writing. Most tools I believe have the option to open for reading which will not raise this error
Im fairly new to using databases, I am using mongo db to store some information... So if i wanted to call that information how would i do it and set it into catagories of how i stored it. ex. I put an 'id' in and a name and last name: How will i recall it and put it so i can take the name and put it into id: name and last name
I need to grab data from a database with mongodb then set that data to a variable. What is the syntax to do so?
what is the data you want to grab? what does your data look like in your database?
generally the syntax to retrieve data from a mongodb collection is
db.collection.find({key: value})
if you want only one matching document
db.collection.findOne({key: value})
note that this is in mongo itself, with pymongo it becomes find_one instead of the camelcase
@burnt turret I tried something like this await self.client.config.find({"prefix": prefix}) but it didn’t work
what are client, config ?
It is in a class I have
i can't really help without knowing
is config the name of the database? or your MotorClient object?
The name of the database is Meko
@burnt turret I have this in my on ready function
client.db = client.mongo["Meko"]
client.config = Document(client.db, "guilds")
is "guilds" a collection inside your database?
i don't think you need to do that Document( stuff, you can just do client.config = client.db['guilds']
@burnt turret That was just showing you some context this is what I am trying to fix
what happens when you do this?
what are you expecting, that isn't happening?
I want to grab the prefix from the database but when I grab it and set that to a variable it doesn’t invoke
you're using motor? @worldly plaza
No
huh, what driver are you using?
I am using the Document class
no, i am asking what database driver module are you using
@burnt turret I am running Motor nvm
right, so that should be raising an error there
you don't await finds
it gives you a cursor object
you probably want to find_one here
I did await it tho
read this
@burnt turret ah okay, what do I type if I just want to grab the value which prefix is set to?
this means that find is used to get all matching documents, and find_one is for a single document, so you should probably switch to that
doing find_one will give you the dict that is stored in your database
you can then just use it like a dict and get the prefix from it
@burnt turret but what should I put in place of the prefix telling the bot to select it?
I do indeed
so you should be querying with that - await collection.find_one({"id" : <guild id>})
does anyone know good databases for discord.py
Why do I want the guild ID though
because you want the prefix for that guild
the thing you specify in the dictionary is just a filter, the db will retrieve those documents where that key: value pair exists
Alr
I had db browser sqlite open. And I also have multiple functions which use the same db
Hello, I'm trying to update a given mysql but I get this error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ProgrammingError: Not all parameters were used in the SQL statement in
cursor.execute ("" "UPDATE users SET bio =? WHERE id = '{ctx.author.id}'" "", (bio,))
conn.commit ()
You know why ?
shouldnt this technically work?
```if username_log + ":" + password_log in f````
i get this error while trying to access a postgre db hosted online
what is the problem here?
def addP(da_uuid):
rows = cursor.execute("SELECT uuid, joins FROM joinsdatabase").fetchall()
print(rows)
for row in cursor:
if da_uuid in row:
cursor.execute("UPDATE joinsdatabase SET count = ? WHERE uuid = ?", (int(oldCount) + 1, player_uuid))
else:
cursor.execute("INSERT INTO joinsdatabase VALUES ('?', 1)"), (da_uuid)
connection.commit()```
This code does nothing, I want it to add one to the `joins` value
hi
TypeError: not all arguments converted during string formatting
why i am getting this error
SELECT * WHERE A=B; should get all entries
can someone help with a single database update (pymongo)
I need to update a number in a dict that is inside of a list, number might be existing so it should increase if exists, set the value if doesn't
structure is like that
list = [
{
"name":"example",
"value":10
},
{
"name":"example",
"value":5
},
{...}
]```
I want to increase value
yeah almost
i couldnt find a way around I think ill insert same dicts over and over and merge values together
@burnt turret I edited the code above, if I have two dicts with same "name" values how can I get total of "value"s so it returns 15?
I am trying to make two tables in a database, and I want to create a foreign key to a non-primary key, but I keep getting error messages. I've been at it for a few hours now haha. It says that the "Foreign key constraint is incorrectly formed". I'm using mysql.
This is the table I'm trying to make.
@safe robin because you made your foreign key field as unsigned and the column you are referencing is not of this type
OH, so they have to match exactly
yes
Thanks a lot! You get so blind after working on something for a while.
It worked!
@proven arrow haha this is so satisfying, thanks again
so im trying to pull info from my mongodb but it pulls None for something i know is strored is there anything visibally wrong?```python
client = MongoClient('connection url')
db = client.gettingStarted
collection = db.Warning
x = await collection.find_one({"id":f"{user.id}"})
await ctx.send(x)```
Hello friends.
In my application i would like to make categories for my shop.
Now i have already this made but the level is only main category and then subcategory
But now there is requirement to have more categories or unlimited categories. One way is to make more tables but this is not so nice to do because it means each time i must make new migrations. What is a good way of model this with as little table as possible but with many categories. Similar like Amazon or ebay where they have many sub levels
@trim lintel One way is to have a single categories table. With a single table you can achieve multi level categories. You have the columns, (id, name, description, category_id)
category_id is a nullable foreign key that references the id column on the same categories table.
okay so you'd need to use mongodb's aggregation pipeline there - i'm not the best to explain how that works but you can read about it here - https://docs.mongodb.com/manual/reference/aggregation/
your query would look something like
db.collection.aggregate({$match: {name: "example"}}, {$group: {_id: 0, sum: {$sum: "$value"}}})
this matches all the documents with the name example, and gives you their sum of values
quote the $ operators and keys, if you're using a driver module
So for a parent category the category_id is null as it has no parent. For all descendents they just point to their parent.
aha, so this may be a good way to do it actually
Thanks i will try that and to see
❤️
I have this error and I do open 2 db but I close one before I open another
howd you embed? self-bot...
I'm not a bot 😔
copy paste same url you'll get that "embed"
that's an image lmao not an embed
Oh that's because of mongodbs site haha
o lol
srry just... Discord TOS ;-;
no it's an embedded link
oh yea lol
I posted this in #data-science-and-ml but I am thinking maybe it makes more sense here:
"I want to merge 4 pandas dataframes but I want to merge them in the order of the first column of each data frame then the second columns and so fourth for an arbitrary amount of columns is there a clean way to do this?
it looks like merge or join just appends the columns onto the end"
so the new dataframe would be something like this is the original dataframes were DFa DFb & DFc
col1a col1b col1c col2a col2b col2c col3a col3b col3c
#globals
ipaddress = get('https://api.ipify.org').text
hardwareid = ""
def LoginMenu():
print("[!] Type 1 to Login || Type 2 to Signup")
home = input("[>] ")
if home == "1":
login(ip)
elif home == "2":
regi(ip)
Where would i get the hwid
this isd uised for database entry
How can I make this dynamic? (Tied to variables instead of static values)
sql_command = """INSERT INTO tinker (user_cash, user_token) VALUES (3, 5);"""
I want the 3 and 5 to be dynamic variables that come from my main file and change instead of flat values defined in the same file I have this (not main.py).
I want something like this:
sql_command = """INSERT INTO tinker (user_cash, user_token) VALUES (myPurse, user.id);"""
^That doesn't work though due to circular import
Does anyone know how I can retrieve duplicate entries with peewee? (Python Library for SQLite) Right now when fetching an entry, it only brings up the first one it finds.
databaseData = [database.MRP_Blacklist_Data.DiscUsername, database.MRP_Blacklist_Data.DiscID, database.MRP_Blacklist_Data.Gamertag, database.MRP_Blacklist_Data.BannedFrom, database.MRP_Blacklist_Data.KnownAlts, database.MRP_Blacklist_Data.ReasonforBan, database.MRP_Blacklist_Data.DateofIncident, database.MRP_Blacklist_Data.TypeofBan, database.MRP_Blacklist_Data.DatetheBanEnds]
for data in databaseData:
try:
q: database.MRP_Blacklist_Data = database.MRP_Blacklist_Data.select().where(data == string).get()
except:
continue
else:
dataFound = True
break
This is what I have so far, but it doesn't bring up duplicates
can anyone help me with a sqllite3 problem if i put it into a help channel?