#databases
1 messages ยท Page 126 of 1
if get = 0?
notice how it says the object is NoneType.
meaning that the dictionary is None
so your if statement should be checking that
but it equals 1
huh
then you should be checking that
either way, that if statement is incorrect
a single = is assignment
== is equality checking
It isn't adding anything.
mydb = myclient["BritishArmy-Moderation"]
mycol = mydb["Warnings"]
reason = Functions.joinSplit(spl[2:])
def GetRank(message):
if HasTheRole(785112522499555369,message) == True: #admin
return "Chief Mod"
elif HasTheRole(793844239506341909,message) == True:
return "Administrator"
elif HasTheRole(785551694670069820,message) == True:
return "Moderator"
high = mycol.find_one(sort=[("WarnID", -1)])
wid = int(high["WarnID"])
mydict = {"WarnID":str(wid + 1),"WarnDate":today.strftime("%d/%m/%Y"),"WarnedName":message.mentions[0].name,"WarnedID":str(message.mentions[0].id),"ModeratorName":message.author.name,"ModeratorID":str(message.author.id),"ModeratorRank":GetRank(message),"Reason":reason,"Test":False}
mycol.insert_one(mydict)```
wid = int(high["WarnID"])
TypeError: 'NoneType' object is not subscriptable```
error just mean that high has nothing in it. so when you try to get value you try to do something on nothing, which gives error
Why is nothing in it?
Cuz
In the database
there is.
because the mycol.find_one(sort=[("WarnID", -1)]) returned none, probably because its incorrect way to use it or the value is not there
anyways i have question
I read EAV model is not so good to use. Is it always like this?
What is a "Database Notification"? I'm making a discord bot for someone and they wanted me to integrate it with some kind of db notification, but when I search it up on google I get no answers.
for pymongo when i query for something but nothing matches
what is returend
like what would mydoc have in it
if there was nothing in it?
and is mydoc a list then
?
Ey, so I wrote:
https://github.com/jimcarreer/dinao#basic-example
And wondering if anyone finds it actually useful (it lets you bind parameterized SQL queries directly to a python function).
i'm using pymongo to do this
but how do i get it to only return the 500 value
this is my code rn
also how do you query in pymongo to check if soemthing exists?
i just used a janky solution of creating a substring haha
looooooooooooooooool
classic
If it is None then it means the record was not found.
Try x.values()
Idk
elif msg.startswith('.kicking'):
await message.delete()
if HasTheRole(793844239506341909,message) == True or HasTheRole(785112522499555369,message) == True:
con = message.content.split()
reason = Functions.joinSplit(con[2:])
try:
them = message.mentions[0]
guild = message.guild
myclient = pymongo.MongoClient("no leak")
mydb = myclient["Moderation"]
mycol = mydb["Kicks"]
userobj = guild.get_member(them.id)
await Functions.SendEmbedFail("Kicked",message,"You were kicked in the British Army for " + reason,message.mentions[0])
await userobj.kick(reason=reason)
loeh = await Functions.SendEmbedSuccess("Kicked",message,"<@" + str(message.mentions[0].id) + "> has been kicked for " + reason + " by " + "<@" + str(message.author.id) + ">",message.channel)
await asyncio.sleep(8)
await loeh.delete()
high = mycol.find_one(sort=[("KickID", -1)])
wid = int(high["KickID"])
mydict = {"KickID":str(wid + 1),"KickDate":today.strftime("%d/%m/%Y"),"KickedName":message.mentions[0].name,"KickedID":str(message.mentions[0].id),"ModeratorName":message.author.name,"ModeratorID":str(message.author.id),"ModeratorRank":GetRank(message),"Reason":"**Kick - **" + reason,"Test":False}
mycol.insert_one(mydict)
except:
awaiterror = await Functions.SendEmbedFail("Error",message,"You need to supply an Mention.\n\n``Example Usage:`` !kick @hidden flax Being mean.",message.channel)
await asyncio.sleep(5)
await awaiterror.delete()```
It's not adding anything to the database.
Code:```py
@commands.Cog.listener()
async def on_message_delete(self, message):
cluster = MongoClient('Mongo URL')
collection = cluster.DataBase_1.settings
for x in collection.find({"_id":message.guild.id}):
logid = x["log"]
print(logid)
guild = get(self.bot.guilds, id=message.guild.id)
log = get(guild.text_channels, id=logid)
if message.content == "":
return
else:
print(message.content)
embed = discord.Embed(timestamp=message.created_at, description=f'**Message Author:** \n<@!{message.author.id}>({message.author.id}) \n\n**Message Channel:**\n<#{message.channel.id}> \n\n**Message Content:**\n`{message.content}`', color=242424)
embed.set_author(name=f"Message Deleted", icon_url=message.author.avatar_url)
embed.set_footer(text='Numix', icon_url=self.config.logo)
await log.send(embed=embed)```
MongoDB:
Hello
I am getting error with something like foreign key but idk why?
Currently i have 4 products in database. I get the error on insert, and the insert it works with 2 of the products, but not the other 2.
This is error:
#1452 - Cannot add or update a child row: a foreign key constraint fails (`caillouxxx`.`order_items`, CONSTRAINT `order_items_product_id_foreign` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE SET NULL)
Insert statement is: ```
insert into order_items (name, quantity, total, discount, order_id, product_id) values ('Apple iPhone X 64GB', 1, 739.99, 0, 51, 4);
The foreign key you are trying to associate with your order item doesn't exist, is what the error is saying.
And you are saying it does, (although it probably doesn't), so can you show your tables or explain how the relations exist between the different tables.
Right so
Products -> SubProducts is 1-M
Orders -> OrderItems is 1-M
And can you show how you created the table order items?
If you no longer have the query you can run SHOW CREATE TABLE order_items to get the statement.
My guess is you have linked orderitems to the wrong product table, since you say it works for 2.
@proven arrow Thanks you were right ๐
it was because wrong table was referenced,
guys i have a problem with my sql
def CheckCustomerExistence(self):
self.cursor.execute(f"SELECT phone_no FROM customers WHERE phone_no='{int(self.SenderDetails[0])}'; ")
print(cursor.fetchall())
error
psycopg2.errors.SyntaxError: syntax error at or near "'1'"
LINE 1: SELECT phone_no FROM customers WHERE phone_no='1';
^
HINT: No operator matches the given name and argument types. You might need to add explicit type casts.
@proven arrow hope u can help me!
How do I update in MongoDB?
@torn sphinx Oh no, don't do that, do cluster = ...
and then bot/client.db = cluster.db_name in your main file, you can use bot/client.db.collection_name anywhere.
Code:```py
@commands.command(alisases=["set-logs", "audit-log"])
async def log(self, ctx, log: discord.TextChannel):
collection = self.db1.DataBase_1.settings
update = {"_id": int(ctx.guild.id), "log": int(log.id)}
collection.update_one(update)```
@rancid badger The query is fine. Most likely errror is because your single quotes might be some different character set.
You should use a parameterised query. 1) Because they are safer and prevent sql injection, and 2) It avoid errors like this as it will handle conversion and binding for you.
For example, the below is how you can do it.
self.cursor.execute("SELECT phone_no FROM customers WHERE phone_no=%s", (int(self.SenderDetails[0]),))
wdym "motor"?
@torn sphinx collection.update_one({"_id": ctx.guild.id}, {"$set": {"log": log.id}})
ok?
Motor: Asynchronous Python driver for MongoDB
It is similar to pymongo, you just have to put await before operations.
why people use mongo for discord bot?
it doesnt even make sense to use it because most people have relational data
I know
and then they have difficulty in trying to use mongo and get support for it
But Mongo isn't "bad" either.
Actually, json is as simple
That is your genuine difficulty as to when someone didn't read the docs.
hmmm but also support is generally less for like mongo
It's intuitive anyway, as it is python dicts.
hi
guys im learning django and reached the pagination part, and now im trying to fetch data from a json file and then put it in the website, but what happens is that only one item gets showed in the website and then i get this error:
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: FOREIGN KEY constraint failed
Does your foreign key exist in the parent table?
is there any way to know?
Just check the parent table to see if the foreign key you were trying to insert exists.
i sent you a DM
Hi, can someone please help me? I just need some help to get this working: ```
inputName = input("Please input your name: ")
sql = "SELECT * FROM accounts WHERE name = inputName"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)``` But when i try using inputName in the sql variable it wont work! Please help!
Your query is a harcoded string.
@maiden light it equals 0
It means the input value is never passed to it. The query string you have stays like how you coded it.
.
Which database driver are you using?
So you would want to use a prepared statement for this.
You can do it like this,
mycursor.execute("select * from accounts where name = %s", (inputName,))```
i will try
Basically this way the value inputname is substituted with %s
guys help please
It is not supposed to be None? If it is None it doesn't exist.
@maiden light everyones ID is in there, and level is set to 1
me?
yes you
storing the amount of messages sent in the levels db
๐ what ๐ is ๐ your ๐ code
find = await db["Scope Level"].find_one({"id": message.author.id})
get = find["level"]
get = find["level"]
TypeError: 'NoneType' object is not subscriptable
and you're telling it to find a int
oh, ok
find = await db["Scope Level"].find_one({"id": str(message.author.id)})
get = find["level"]
is that better @brazen charm
tias
now I get this error ```
TypeError: update_one() missing 1 required positional argument: 'update'
Oh! Why didn't I notice ://
Show your code where it uses update_one
It failed to update
record = {"id": str(user), "level": get+1}
await db["Scope Level"].update_one(record)
Correct way is :
await db["Scope Level"].update_one({"id": str(user)}, {"$inc": {"get": 1}})
@fading breach
$inc means increase
It will add 1 to get
ok
im using motor though
Yes it would be, I already said what is necessary above in this channel
ok
the only difference is you await the query
Just read everything
btw user = str(message.author.id)
I have
Btw there are other methods, like $set which sets it to what you give, read docs :/
Nice
hi so im using docker-compose to create a reboot feature where i can reboot my file remotely,
bot.pg_con = await asyncpg.create_pool(host='54.212.127.203', database='warns', user='admin', password='password')```
i added host to my postgres conn pool and made it the ip of my vps, then, when i run the file using ``sudo docker-compose up``
i get this error: https://mystb.in/PortraitConflictsJuly.error
anyone know why?
https://cdn.discordapp.com/attachments/775507084288065557/795332697651150898/Screen_Shot_2021-01-03_at_8.48.01_AM.png
@lethal depot Is your code is running from your vps?
my db is on my vps
And your code?
So then you can use localhost as the address
I see, well am unsure how docker works since i dont use it. Other thing you could do is open the database to listen on that IP address
Similar to how you do it for remote connection
listen_addresses?
Yes i think thats what postgres has it under
this code doesnt do anything can anyone help?
what do you expect it to do?
try inserting some data
i think it will show up only once you insert some data into it
yeah, i think mongo only actually "creates" the collection once you put some data in it
it did...
thanks dude
thank you so much...
i wouldnt have bothered you but I never use mongodb on python ๐
๐ all good, afaik mongo does this for both databases and collections - only creates it once you put some data in it
Using aiomysql what is the proper way to prepare statements to avoid sql injection attacks? Please tag on reply.
@maiden light how can I retrieve the top levels from mongo
for example this is my db:
I want to retrieve the top 5 levels and IDs and return them back as a string for a leaderboard command
Security considerations for password storage are generally more holistic than where they are stored.
heroku config:set DB_URL=YOUR_OWN_DB_URI
heroku config:set TOKEN_SECRET=YOUR_OWN_SECRET
Can someone please help me find these variables on my heroku client?
@pure cypress or you bro, i seen that yall know about systemmd.
You can loop through all data like :
async for find in bot.db["Collection name"].find():
do something with data, like append it to a list, and use list.sort with reverse and a key to get top 5
I forgot a simpler way to do it
it returns true even when the username and password is not in the database. how do i fix this?
That's because even if it doesn't exist the query still returns a result of 0. So your if statement will.pass because there was a result there.
Also you don't need to be doing exists for that query. An easier way is to do, SELECT COUNT(*) FROM users WHERE name=? AND password=? LIMIT 1),
This will return a value of 1 or 0, of how many rows were matched.
i will try it later, thank you
it returns an object, not a number. how do i use that?
You can do if cur.fetchone()[0] > 0 : // match found
@torn sphinx go ahead and ask your question. Anyone familiar with it can respond
nvm i solved
๐
@maiden light TypeError: 'AsyncIOMotorCursor' object is not iterable
@commands.command()
async def leaderboard(self, ctx):
for find in db["Kingdoms-Level"].find():
return find
Hey @torn sphinx!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Hi, I really need some help please! I am using requests to do an api call to grab data from 2010-2020 separately to enter 10 separate entries into a db for each year. When I first ran the code only 1 entry from 2010 was entered into the db instead of 1 for each year. I ran the code again then my custom error msg 'print the root error message' printed out 10 times. I have attached the file below. I don't know what I am doing wrong and a solution would be a lifesaver!
on getting a value through tkinter i just get an emptystring for everything
can somebody plz help?
๐
Hi! If I use a aiomysql connection pool ( PyMySQL ), my app will just get stuck after a while when requesting a connection. Do you know how to fix this?
async for not for
ok
Anyone have examples for a database querying website with a python backend
Actually that would be kinda worse than just a simpler PHP backend script
Hi, I am trying to make a list of the best scores in my DB (mongodb). I need the names and the scores.
I don't know what to do :(
database
pls help me, I cant get to install mysqlclient, Ive been trying to solve for this weeks now, and I just dont get why it cant get installed. My version of python is 3.8 and I have the latest version of pip
Hello guys I've just opened a new github discussions about System Design
Feel free to join and contribute to this discussion by sharing thoughts,tips and other stuffs
The aim of these discussions is to fit the gaps around System Design backgrounds, misunderstandings
Please help contribute, giving your thoughts and feedback I'll be waiting for you right there
https://github.com/HipsterSantos/system-design-primer/discussions/1
pickleDB good for production ?
I'm planning on a project that will have thousands of DB entries a minute. I understand that that many DB commits in sqlite is a bad idea though due to the speed limitations.
How should I restrict it? A timer loop every 60 seconds? or a counter to save every hundred entries?
@torn sphinx You should not restrict it, you should use a different Db. SQLite is not meant for that kind of operations. I would recommend using postgresql db for a write-heavy application. The database will handle the operations properly
Should I though... because SQLite can handle many thousands of entries a second... It just can't write to disk that often...
also I'm still working on bach degree...
lol
I don't really want to have to deal with setting up a server
and wanted to be able to just upload easily.
"Actually, SQLite will easily do 50,000 or more INSERT statements per second on an average desktop computer. But it will only do a few dozen transactions per second. Transaction speed is limited by the rotational speed of your disk drive. A transaction normally requires two complete rotations of the disk platter, which on a 7200RPM disk drive limits you to about 60 transactions per second. " Hum this sounds like I could just drop it into a ram-disk... and get really good speed.
If you don't care about persistence, you don't need a file at all. You can use sqlite3.connect(":memory:") to create a purely in-memory database
@torn sphinx
I found that but I do need persistance and can't find a way to save that to a file
isolation_level in sqlite has an incremental and defered option. I think one of those may do what I want.
If you need persistence, then a ramdisk seems like a bad idea. Everything will be lost if the machine crashes.
yea that is not a good option.
The usual performance tip is to make each SQL statement do as much work as possible. If you need to insert 1000 rows, do it in 1 transaction instead of 1000. Is you need to delete 1000 rows, try to do it in 1 statement, or at least 1 transaction. Etc.
And make sure that your data model is properly normalized, so that you aren't writing more than necessary.
You mention thousand of writes but are they all concurrent writes?
Hello guys!
Anyone MongoDB dev?
I am a making a discord bot, and i want to delete a entry after x days
Anyone know how can i?
Because what you said before that sqlite can handle many per second, although true because writes don't take that long, however that doesn't change the fact that sqlite can only have a single writer at any given time. For concurrent writes in the many thousands a client server would always be better, unless you have a different approach on how you handle the writes.
If it's only one server process that wants to write to the database in the first place, then adding concurrency into the mix isn't likely to speed things up much, I suspect
Help me!
yes all one connection
but I am using aiosqlite
What I meant was how many users/processes trying to write at once? You should have a read of here https://www.sqlite.org/whentouse.html
It should help you decide which you need, and they cover this sort of issue as well.
Key value pairs have syntax like, key : value. You have something else going on there.
Just the one process
So all the writes are queued then.
Then sqlite should be fine, but just do what godlykeek said regarding the statements doing as little work. Or write in batches.
And reads are fine.
batches were my original plan. How should I restrict it? A timer loop every 60 seconds? or a counter to save every hundred entries?
I cant reduce the inserts
well I could queue them elsewhere... but that seems slower
every 10 should do for now...
@torn sphinx batch insert would just be temporarily storing that data to be inserted somewhere for example in memory, and then having something like a task/loop or whatever is appropriate in your application to insert that data. And when you insert in batch you should insert using executemany, which would be more efficient and quicker than a bunch of executes.
I think I need to make a test benchmark program...
I will probably have to go with an insert many though. Thank you
im getting the following error while trying to insert new records to a table in SQL server-
Invalid column name 'value_1'.```
code to create table-
```create table "table_name"
("col_1" varchar(256) not null,
"col_2" varchar(16) not null,
"a_date" datetime not null,
primary key("col1"));```
code to insert new record-
```insert into table_name(col_1, col_2, a_date)
values("value_1", "value_2", getdate());```
can anyone let me know what i am doing wrong
@proven arrow How do I make this work?
Absolutely fucking not, NEVER us pickle for production like that
Not JSON, Not Pickle not Shelve etc...
pick a actual DB for that
the $ operators have to be passed as strings in pymongo/motor
"$addToSet"
#databases message pls help...
Anyone knows how to completed remove the sql pluggable database without dropping every single table?
could be administrative right issue?
run cmd as an admin
then repeat, i know very silly recommendation, but sometimes people forget that
not strictly about python, but im looking for a database thats hosted in the cloud for an application im building. Whats the best database to use?
hoping its cheap too ยฏ_(ใ)_/ยฏ
The cheapest thing that has the features you need
yeah
best database and free
How?
hey guys did sqlite3 do something with db format?
sqlite3.DatabaseError: file is not a database
no problem when create it with sqlite or sql format
documentation uses db format
Thanks
cool
Ok thanks man
did it actually work?
stats = await levelling.find_one({"guild": message.guild.id})
^
SyntaxError: 'await' outside async function
``` Anyone what to do?
nvm i solved
Anyone know PostgreSQL?
I am getting an error:
RuntimeError: column "purchases.company_name" must appear in the GROUP BY clause or be used in an aggregate function
On line:
db.execute("SELECT SUM(shares), ticker, company_name FROM purchases WHERE id = ? GROUP BY ticker HAVING SUM(shares) > 0;", (session["user_id"]))
It works in SQLite though
rankings = await levelling.find().sort("xp", -1)
it says await cannot be used ๐ฆ
and also
rankings = await levelling.find().sort("xp", -1)
i = 1
embed = discord.Embed(title='Rankings', color=0xff0000)
for x in rankings:
try:
temp = ctx.guild.get_member(x["id"])
tempxp = x["xp"]
embed.add_field(
name=f"{i} : {temp.name}",
value=f"Total Xp: {tempxp}",
inline=False)
i += 1
Not iterable ๐ฆ
@torn sphinx Do you know what to do about this error?
You're selecting company_name, but you're aggregating multiple rows together using group by ticker. It won't let you do that because it doesn't know, for each set of rows with a given ticker, which one to take the company_name from.
But they are all the same
Would this change the results?
GROUP BY ticker, company_name
It doesn't know that they'll all be the same
It got rid of the error, but I don't want it to mess up the statement
Yes, that's a reasonable way to fix it
Thanks!
That will give one result row power unique ticker/company name combination. And if they're one to one, that's still only one result row per ticker.
Alternatively, you could do:
SELECT SUM(shares), ticker, max(company_name) FROM purchases WHERE id = ? GROUP BY ticker HAVING SUM(shares) > 0;
Ok
And to get this value:
stock['SUM(shares)']
Do I have to change that?
It is throwing a key error
That depends on the database, I'm not sure.
You could try select sum(shares) as num_shares
I am switching mine from SQLite to Postgresql
Could I also do
as sum(shares)?
So I don't have to change anything?
That should let you get it with stock["num_shares"]
Can anyone help me? I am switching from pymongo to motor
I'm not sure. Never used postgresql, don't know if it minds parentheses in its column names or not.
Ok
You could also just print(stock) to see what you got
It could be it was all lowercase instead of mixed case, or something.
Oh yeah, thanks!
@frail imp That's a very broad question, you should either ask a more specific question, about what part you're stuck on, or look up a tutorial for it
i am unable to
Unable to what?
unable to get a tutorial for dbs with discord.py
Do you know how to use database with python?
Just with Python in general, not discord.py
Guys
i need help
My MYsql losses Connection Automatically
am using Heroku's ClearDB mysql.
return stops the whole function and the loop becomes pointless, append it to a list, use a key and list.sort to get top 5.
Anyone mondoDB?
@torn sphinx Pymongo is blocking, install Motor and read that
Just read that ://
kk
is here busy or can i ask a question
i have table with foreign key, when inserting into table with python how can i pass None or whatever to that column with foreign key?
def somequerymethod(val=None):
query = f"""INSERT INTO sometable(somecolumn) VALUES ({val})"""
cursor.execute(query)
but passing None or 0 doesn't work
If you want it to be null during insert then you can just leave out that column, because it will then get inserted as null automatically.
The reason it doesnt work for you in the code above is because you passed None as a string. It needs to be of the None type.
This would work,
query = "INSERT INTO sometable(somecolumn) VALUES (?)"
cursor.execute(query, (None,))
Ok, thx
hey guys, Does anyone know of a way to display MySQl data on Tkinter's window?
@timber sphinx connect to your database, query it and get your data
When i get requests i insert the data into my database, my question is:
lets say if i get 20 requests per second, would my synchronous database class have problem writing all the data without any delay or loss?
I did, but it doesn't display anything (also i'd ask for your papers rn but it isn't the right time...)
The thing is i don't know if there is a way to display the entire table on tkinter.๐ . I tried a few queries but it kept throwing an error
@maiden light I get this error py @commands.command() async def leaderboard(self, ctx): async for find in db["Kingdoms-Level"].find(): find.append() find.sort(reverse = True, limit = 5) ```
find.append()
AttributeError: 'dict' object has no attribute 'append'
you cant append to dictionary
at least not like that
so from what i understand
db["Kingdoms_level"].find() returns you a dictionary
in order to add key, value to a dictionary
you do
mydict["mykey"] = "myvalue"
.append method is for lists
when you loop through db["kingodms-level"].find(), each iteration returns you a dictionary
so if you want to add new data in each iteration, then yes you have to set key and value
i don't know what you are trying to do, you can set it to anything
ok
I am considering switching to aiosqlite because of the fact that my application is async, and obviously that would be ideal. My question is, can there be multiple aiosqlite connections active and interacting with a db at the same time, or would that cause errors? Also, if I have one application w/ aiosqlite connections, but another application connected to the same db w/ normal sqlite module, would both applications interacting w/ the db at same time cause an issue? Please @ me when responding to my questions, and thank you.
can I do myDict.sort()?
no
what should I use then
you wouldn't need to sort it because you acces dictionary items with keys
you cant do mydict[0]
it would look for key 0
can I convert a dictionary into a list?
point of dictionary is, its with key and value
if i were you, i would debug and see what db["Kingdoms-Level"].find() returns
now I have this ```py
@commands.command()
async def leaderboard(self, ctx):
async for find in db["Kingdoms-Level"].find():
myDict["1"] = "1"
myDict was an example ๐
what exactly are you trying to achieve here?
people = []
async for ... :
people.append(find)
Then use a key, and sort people.
sort all the levels from highest to lowest
but have a limit of only keeping 5
def key(d):
leaderboard = []
return d["levels"]
@commands.command()
async def leaderboard(self, ctx):
async for find in db["Kingdoms-Level"].find():
leaderboard.append(find)
leaderboard.sort(key=key, reverse=True)
yeah you can do that
def key(d):
return d["balance"]
people.sort(key=key, reverse=True, ...)
You need a key :/
That gives it balance, or bank + balance.
should I replace balance with levels
I guess yeah
That sort line should be outside of loop
Why is leaderboard = [] randomly inside key, put it under the key function.
should the function be inside or outside
indents are weird
Inside
Put the sort line after you have prepared leaderboard, under the loop
guys not to be ass but this is database channel, you would get better help in help channels
@commands.command()
async def leaderboard(self, ctx):
def key(d):
leaderboard = []
return d["levels"]
async for find in db["Kingdoms-Level"].find():
leaderboard.append(find)
leaderboard.sort(key=key, reverse=True)
leaderboard = leaderboard[:5]
print(leaderboard)
@mental quiver Indents mess up in discord
Huh, I have not had that happen to me. Strange.
Fine, but the key function should be inside the command.
It doesn't matter
leaderboard = leaderboard[:5] I guess, after you have sorted
is the code fine now
Does limit stop at first match?
Or just limit the overall results to a particular shape
๐
Anyone on #databases message rq? I think its a fairly simple set of questions, just had some issues finding clear answers online.
And if you are talking about LIMIT <amt> in sql cmds @real timber, it limits the results to the amt given.
now I need to make it a discord.py embed
But
discord.py docs.
its easy
Cheers
ill show u
You again have randomly that leaderboard = [] line in key @fading breach
ok
I already know ow to do it
ah ok then
I wanted to get the first match from a column but big query doesn't have TOP command, so I used
Select count(*) from table where col = value
It seems expensive though
Put leaderboard = [] under and outside key @fading breach
Or before, doesn't matter
ok
From what I know, this would get the amount of matches to the WHERE, rather than the actual results. Is that your intention?
Yes, then I can test if test if it's zero or not zero
But I only need logic, so first match is fine
got ya. then from what I know that looks good. and yeah I think if you add LIMIT 1 to the end of that, itll stop at first result.
Ok, I'm not sure what the behaviour of any( ) in python is referred to as (stop at first match?) But that's what I want
So if there's a column with 1 billion rows, it'll only check 1 row if the value is the first element
@fading breach Btw, this is what I see
The @commands.command() and async def start from the same point, right?
I've got a suspicion limit will process all the data and then just return the first n, rather than stopping at first match. I'll check in bigquery in a bit though
Yeah just tested it, Limit doesnt work on counts. hmm
To be clear, I'm not interested in the count exactly, I'm interested in testing whether a value is in a column, it's just count provides me something I can test
A return value of 0 or 1 would be fine, rather than 0 or the total count (which I currently get)
right. What is the size of the table btw? also, I would recommend only selecting the column you are interested in as well to further increase speed, like SELECT col_name FROM table_name WHERE col_name = value.
Table atm is small, few million, but it'll grow
Yeah didnt find much online that is super helpful, though hopefully this could help: https://stackoverflow.com/questions/33889922/how-to-get-the-number-of-total-results-when-there-is-limit-in-query
Wish I could help more, but I am just not experienced enough in sql. GL.
cheers , i don't have a limit in the query, i'm just trying to break on first match
is this vulnerable to sql injection?
cursor.execute(f"SELECT * FROM SOMETABLE WHERE name={yourname}")
is yourname an input()?
if yes then yes
use cursor.execute("SELECT * FROM sometable WHERE name = ?", (yourname,))
yourname is passed as argument into a method
ok thanks
if i have a Names table and names are set to Unique, when i try to insert new names into table and duplicate name exists, is it fine if i just use try/except and pass in exception
or should check if name exists then add?
Do you want something to happen in the except, other than just pass?
no just pass, because without try/except it will raise exception becaue of unique column
Right ok so you can do that or you can also have the database ignore the error if there is a unique constraint violation, and so you don't need to handle it in your code.
What database are you using?
Ok so MySQL has INSERT IGNORE
hi can someone help me with some sqllite 3 code
sql = "UPDATE " + cat + " SET Item = " + iteminp + ", Price = "+ priceinp +" WHERE Item = " + orgitem
this is giving the error "no column : iteminp"
you're missing something
any idea what it is
sql = "UPDATE ? SET Item = ?, Price = ? WHERE Item = ?"
vals = (itemcat, ite, pricee, ManageMenu.item)
cur.execute(sql, vals)
ive also tried this
this gives me a different error
what is the error with that second version?
near "?": syntax error
sql = "UPDATE ? SET Item = ?, Price = ? WHERE Item = ?"
vals = (itemcat, ite, pricee, ManageMenu.item)
cur.execute(sql, vals)
^ correct?
I'm not certain dynamically inserting the table name is supported syntax (UPDATE ?)
you may want to insert it using an f-string instead:
sql = f"UPDATE {itemcat} ..."
wdym?
it's the same as doing 'UPDATE {} ...'.format(itemcat)
sql = "UPDATE " + itemcat + " SET Item = ?, Price = ? WHERE Item = ?"
or 'UPDATE ' + itemcat
does it have to be '
Hello
i have problem s SQLite3
when i try to create no sqlite3 db in folder other than my home
i got error unable to open database file
i need someone who can talk and help me
Anyone used mongodb?
is it possible to find all "user_ids" in a collection then add the results to a list?
for x in collection.find({}, {"_id": 0, "user_id": 1}):
test_list = list(x.values())
print(test_list)
tried this but get this :
[77413093111111111]
[1111111111111111111]
i want it to be
[77413093111111111, 1111111111111111111]
@hearty jungle create an empty list at the start and append
however...think you just want list(collection.find({}, {"_id": 0, "user_id": 1}))
@shell ocean cheers.
im trying to get the list of ids.
for x in collection.find({}, {"_id": 0, "user_id": 1}):
print(x)
test = x["user_id"]
print(list(test))
test gives me the values of the user ids. However, when trying to put them in a list i get this:
TypeError: 'int' object is not iterable
i tried "list(collection.find({}, {"_id": 0, "user_id": 1}))"
but idk how i would just extract the numbers
listname = []
for x in collection.find({"_id": 0}, {"user_id": 1}):
listname.append(x)
await ctx.send(listname)```
@hearty jungle try this
can someone help with this:
https://stackoverflow.com/questions/65607835/when-fucntion-recieve-text-its-working-but-if-recieve-x-when-x-text-cant-ru
i have a function grab_funds(ticker) that get a stock symbol and return certain fundamental info in a dataFrame.
def grab_funds(ticker):
key='key1234'
base_url = 'https://www.alphavantag...
?
@bot.command()
async def dbtest(ctx,user_id,reason=str):
connection = sqlite3.connect("warns.db")
crsr = connection.cursor()
create_table = """CREATE TABLE warns (
warnnum INTEGER PRIMARY KEY NOT NULL,
user_id text NOT NULL,
reason text NOT NULL
);"""
add_values = (f'INSERT INTO warns (user_id,reason) VALUES({user_id} , {reason})')
select_values_2 = """SELECT warnnum FROM warns"""
crsr.execute(add_values)
connection.commit()
crsr.execute(select_values_2)
getting_id = crsr.fetchall()
getting_id_2 = getting_id[-1]
gotten_id = getting_id_2[0]
connection.commit()
select_values = (f"""SELECT * FROM warns WHERE warnnum = {gotten_id};""")
crsr.execute(select_values)
ans = crsr.fetchall()
tuple_ans = ans[0]
warnnum = tuple_ans[0]
user_id = int(tuple_ans[1])
reason = tuple_ans[2]
connection.commit()
connection.close()
print(ans)
``` my code to connect to sql db in python
the error:
Ignoring exception in command dbtest:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 69, in dbtest
crsr.execute(add_values)
sqlite3.OperationalError: near "<": syntax error
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 859, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/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: OperationalError: near "<": syntax error
sqlite 3
ping whenever
hey guys
i'm just wondering
is it possible to to use a variable to insert information into MySQL
What kind of variable? One that you define and then use in a query?
You can do it from python using a prepared statement, or if you want to do it purely MySQL then you can have temporary user defined variables as explained here, https://dev.mysql.com/doc/refman/8.0/en/user-variables.html
If you want to do it from python using prepared statement then you can do it as follows:
x = 5
cursor.execute("INSERT INTO table VALUES(%s)", (x,))
Aight will try this out
gimme a few
The %s might be different depending on what library you use to connect to mysql but basically what it does is replaces the values you give as the second argument in order.
I'm getting an error that says:
Python 'entry' cannot be converted to a MySQL type.
What data type is your value?
There are 4 values
3 are varchars, and 1 is a Bigint
cursor.execute("INSERT INTO tables (yourTableHeaders)VALUES(%s)",(x))
it should lok like this
Then can you show the code, the issue is your passing an invalid type from python to mysql
yeah i kinda missed the table headers
You only need column names if your inserting in a subset of columns
i'll try it out and let you know if it works
Yup still getting the same error
but my code is damn huge
its prolly 250 lines
thats not that huge
Well as I said your error is saying your trying to insert a entry type of object, and MySQL does not understand what that is.
Well this is my first time (and most likely my last) using MySQL and Python for a school project๐
So without code it's not easy to help. Anyways I got to go for a bit so you can ask here for someone else.
so is there any way to change it such that MySQL will understand it?
Give it the correct types
yeah show the code or the part where you have the variable and the query so we undrestand the picture
ok
before i send it, I'm using Tkinter to input the values
ok
def to_add():
nW1=Toplevel(top)
c1=mycon.cursor()
Np=Label(nW1,text='----------ADD THE DETAILS BELOW----------')
Np.grid(row=1,column=2)
global ans1
global ans2
global ans3
global ans4
det1 = Label(nW1,text='Enter the Products name')
det1.grid(row=3,column=1)
ans1=Entry(nW1,bd=5)
ans1.grid(row=3,column=3)
det2=Label(nW1,text='Enter the Product number')
det2.grid(row=4 ,column=1 )
ans2=Entry(nW1,bd=5)
ans2.grid(row= 4,column= 3)
det3=Label(nW1,text='Enter the stock')
det3.grid(row= 5,column=1 )
ans3=Entry(nW1,bd=5)
ans3.grid(row=5 ,column= 3)
det4=Label(nW1,text='Enter the price')
det4.grid(row=6 ,column=1 )
ans4=Entry(nW1,bd=5)
ans4.grid(row=6 ,column=3 )
pro=Button(nW1,text="Continue",command=add_products)
pro.grid(row=10,column=2)
def add_products():
c1.execute("insert into Products(Product_name,Product_no,Stock,Price) values(%s,%s,%s,%s",(ans1,ans2,ans3,ans4))
mycon.commit()
msg1=Label(nW1,text='Product has been succesfully added')
msg1.grid(row=7,column=2)
L=Button(nW1,text='Exit',command=close_tab)
L.grid(row=8,column=1)
try c1.execute("insert into Products(Product_name,Product_no,Stock,Price) values(%s,%s,%s,%s",(str(ans1),str(ans2),str(ans3),str(ans4)))
assuming your database types are all string
not all of them are strings though...
str() for string
but i'll do it for those which are
thanks!, will correct that as well
TypeError: int() argument must be a string, a bytes-like object or a number, not 'Entry'
this is what i get on correcting it ๐ฆ
when i make it a string it says incorrect integer value
so i guess i'll have to change the int value to a str
no dont change anything
try c1.execute("insert into Products(Product_name,Product_no,Stock,Price) values(%s,%s,%s,%s)",(ans1.get(),ans2.get(),ans3.get(),ans4.get()))
this should do it
you were passing the entry object, but you needed the value
thus entry.get()
returns the value
aight
it'll work cos i've made ans1,ans2,ans3 and ans4 global
just give me a momenr
*moment
Yup it Works
๐
THANK YOU SO MUCH MATE
I CAN FINALLY FINISH MY PROJECT!!!๐
@red sparrow one last thing
for updating and deleting records i can use the same thing right
That is
c1.execute(delete from Products where Product_no(%s)",(R1.get()))
Can anyone tell me if i can do this?
sorry
anyways wym the same thing
%s and <object>.get() thing
this is what i mean....
why dont u just use ? or : format?
its been years since I used %s so thats a bit confusing
oh alright
but 'll have to correct it in a lot of places, so not looking to change it for now.
c.execute("select * from table where col = ? and col2 = ? and col3 = ?", [firstPlaceholderValue, secondPlaceholderValue, thirdPlaceholderValue])`
```or
```py
c.execute("select * from table where col = :col1 and col2 = :col2 and col3 = col:3", {col1: firstPlaceholderValue, col2: secondPlaceholderValue, col3: thirdPlaceholderValue])
isnt this easier?
more readable
anyways @red sparrow can you hmu on pc when you see this?
thanks mate!
Because different libraries have their own implementation of what characters are used for the placeholders. ? would not work here
all sqlite libraries have the same execute method!?!?
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s' at line 1
This is the error i got on trying the same thing for deleting a record
@proven arrow any idea to solve this issue
You need to provide the code, otherwise i will just repeat what your error already told you.
lol aight gimme a moment
`def to_remove():
global R1
nW2=Toplevel(top)
c1=mycon.cursor()
D1=Label(nW2,text="Enter the product number you want to remove completely")
D1.grid(row=1,column=1)
R1=Entry(nW2,bd=10)
R1.grid(row=1,column=3)
pro=Button(nW2,text="Continue",command=delete_products)
pro.grid(row=2,column=1)
def delete_products():
nW2=Toplevel(top)
c1.execute("DELETE from Products WHERE Product_no =%s",(R1.get()))
mycon.commit()
msg2=Label(nW2,text='Product has been removed')
msg2.grid(row=3,column=1)
L1=Button(nW2,text="exit",command=close_tab)
L1.grid(row=5,column=3)`
Your parameters need to be passed as a tuple/list.
c1.execute("DELETE from Products WHERE Product_no =%s",(R1.get(),)) would work.
(1) is just an int, (1,) is a tuple where first value is an int. It needs something it can iterate through for it to work.
oh ok
@proven arrow one last problem
.
def update_products():
nW3=Toplevel(top)
if R2.get()==N:
U1=Label(nW3,text="enter a new product name")
U1.grid(row=4,column=1)
U2=Entry(nW3,bd=15)
U2.grid(row=4,column=3)
c1.execute('Update Products SET Product_name=%s',(U2.get(),), 'WHERE Product_no =%s',(E1.get(),))
mycon.commit()
msg3=Label(nW3,text="Details updated")
msg3.grid(row=5,column=3)
L2=Button(nW3,text="exit",command=close_tab)
L2.grid(row=5,column=3)
elif R2.get()==S:
U3=Label(nW3,text="enter the new stock number available")
U3.grid(row=4,column=1)
U4=Entry(nW3,bd=15)
U4.grid(row=4,column=3)
c1.execute('Update Products SET Stock=%s',(U3.get(),), 'WHERE Product_no =%s'(E1.get(),))
mycon.commit()
msg5=Label(nW3,text="Details updated")
msg5.grid(row=5,column=3)
L3=Button(nW3,text="exit",command=close_tab)
L3.grid(row=5,column=3)
elif R2.get()==P:
U5=Label(nW3,text="enter the new price")
U5.grid(row=4,column=1)
U6=Entry(nW3,bd=15)
U6.grid(row=4,column=3)
c1.execute('Update Products SET Product_name=%s'(U2.get(),),' WHERE Product_no =%s',(E1.get(),))
mycon.commit()
msg4=Label(nW3,text="Details updated")
msg4.grid(row=5,column=3)
L4=Button(nW3,text="exit",command=close_tab)
L4.grid(row=5,column=3)
else:
U1=Label(top,text="Wrong option, restart to update")
U1.grid(row=4,column=1)
L2=Button(top,text="exit",command=close_tab)
L2.grid(row=5,column=3)
why am i getting this error?:
NameError: name 'P' is not defined
Didn't I define P correctly?
Thats a mess to read, but if it says you didnt define it then you will have not defined it anywhere.
And i dont see P defined anywhere
And your update statements are wrong
The query is a whole, and not to be seperated like whatever you had going on there
oh okay
but since there are 2 values, i thoguht separating the query would be a good idea
But its 1 query
so is there any way to take 2 separate values and enter it as 1 query?
use multiple placeholders
like this?
yes but you would use %s and not ?
why ping :reeee:
sorry man, but had to quote you to understand something.
And thanks for typing that ๐
still getting
[{'user_id': 774130931245645857}, {'user_id': 1111111111111111111}]
im just wanting the numbers.
then irate through it
listname = []
for x in collection.find({"_id": 0}, {"user_id": 1}):
listname.append(x["user_id"])
await ctx.send(listname)```
Hello their, when i create table in my db file i have this line created.
My code.
Hey I'm programming a Discord Bot (this is not related to discord) In which I want to recover the energy of all the players present in the database every ten minutes. My problem is I have to do a lot of requests :
-One to get all the ids in the database :
then in a for list with all the ids :
-Two to fetch the Energy value (current energy value of the player) and Stamina value (max energy of the player)
then one to modify the data if the energy is lower than the stamina
My question is : can I do this with only one request and will this be five time faster ?
It currently takes half a second with four users, I'm afraid it would take hours with a lot more users in the database
I have a table called "userdata"
it contains many fields, with the three important ones here being "id" (integer), "Energy" (integer) and "Stamina" (integer)
I'm using sqlite3 with python
Tl;DR : can I do with only one request "Increment the energy value for all the users in the database only if the energy value of this user is lower than the stamina value of this user" and if so, how ?
That is because you used auto increment for your primary key. So it would make that table, https://sqlite.org/autoinc.html
You can do this with a single UPDATE query. For ex, Update users set energy = energy + your_energy_amount where energy < stamina; where your_energy_amount is the value you want to increase it by
Okay thx!
Thanks a lot !
Im trying to setup a db for a small project im working on
For some reason it's trying to do '' in the query
and that returns an error
what error?
What version of mysql are you using?
Im not sure if thats a phymyadmin related, but generally it should replace the ' ' with NULL so it auto increments
Manually should work, other reasons why it might not be working might be you have strict mode enabled.
Guys if i had to make a login system using MySQL and Tkinter, what should i use to validate the username and password i enter to the ones on MySQL table?
@timber sphinx You can select the count(*) where the username and password equals the values you are testing against. This way the query will return you a value of 1 or 0 depending on if it exists or not.
Also you should index the username column for quick lookup and to avoid a full table scan if you haven't already done so.
I need to query to find rows where one row has the same key as multiple other rows in another column. gah semi complex queries hurt my brain.
-----|-----
. 1 | p
. 2 | k
. 2 | n
. 3 | k
. 6 | l
. 2 | p
where querying would give 2=P,N
oh I don't think I can do this with one query
will have to loop query.
ok thats easy then
i need help
should K not be in that list?
If so then you can use group concat
well no K was going to be the other search
basically I have a list of user ids and a list of channels
and I want to be able to check a channel and find all users who have posted in other channels
so K would be the search key
I didn't mention that though
what I will have to do is loop through members who have posted in the search channel and for each of those check what other channels
Then K does not belong in that column
no it does. that is accurate sample input
simplified
I mean my list of messages has a channel column and every channel is there lol
Hello
hi
I have a question about structure
so basically should i put my database code inside my class that takes user input and gives user output or somewhere else
Well that is one way to do it, but not always the best.
Generally the database stuff lies separately in whats known as the data access layer. So it is separate from your controllers (the class that you say does your input/output with the user). This helps decouple your controllers from the database one step further.
This helps keep your controllers thin, and unaware of your database implementation, and also keeps things DRY.
Oh
People generally adopt some kind of design pattern like the Repository pattern, but end of the day how you implement it will depend on your project that you are working on.
oK, well this project is for an assignment so idk if it matters. But project is a web app.
Yeah such things are quite common in web apps. Whether it provides any advantage to you maybe you should check your assignment spec, to see what it grades you on.
okie
i will try to find out but some people said to do this in some tutorials so i was confused a little
asyncpg.exceptions._base.InterfaceError: unsupported authentication method requested by the server: 10 hey im getting problem with asyncpg
what should i check and what can be causing this?
i cant find anything on stackoverflow ;v
import sqlite3
conn = sqlite3.connect("customers.db")
c = conn.cursor()
many_customers = [
('Billy','Hanes','B@outlook.com'),
('West','Brown','Brown@gmail.com'),
('lax','Gaue','lax@me.com'),
]
c.executemany("INSERT INTO customers VALUES (?,?,?)",many_customers)
print(c.fetchall())
print("saved")
conn.commit()
conn.close()```
i ran this like 100 times and it wont add data to database
i deleted it and tried again so many times
it worked before like a week ago
@worthy geyser
This isn't a help channel. Type something in #help-burrito
hello , I'm currently using mongodb as a database , and i noticed that it's quite slow when it it come to accessing it , is there any advice , or ways to make it faster , or even suggestion of other databases ??
Have you tried MySQL?
no , I haven't
So something like
c1.execute("SELECT COUNT(*) FROM EMPLOYEE WHERE Name= %s and Password = %s",(username,password,))
does this work?
cos i tried it and got a programming error
why not give it a try?
cos so far i've not experienced any slow processing from MySQL
i have a list structured like this:
dic=[
{
"obj1": value1,
"obj2": value2,
},```
how would i edit obj2 in mongodb (pymongo)? edit it to lets say `newvalue`
how would i edit this? https://media.discordapp.net/attachments/796532751385100318/796926869592866846/unknown.png
(with pymongo)
do it like that c1.execute("SELECT * FROM EMPLOYEE WHERE Name = %s and Password = %s",(username,password,))
yup done that
don't worry mate i figured it out
thanks man! ๐
you would need to use {"$set": {"key": {"key": "thing"}}}
well actual
nvm its a array didnt notice that
you'd need to update the list yourself and then
{"$set": {"roles": [new array goes here n stuff]}}
you can if you really want do it via mongo queries but its a bit more complicated
you can do .update_one({"roles.roleid": role_id}, {"$set": {"roles.$.roleid": "newvalue"}}) @glad sleet
Who can help me with structuring MongoDB? With structuring .json
For my project
So em
I want to have a key value โplanโ in my json
If a plan is default, there is no need to place it for the user?
Like
id: 1
plan: default
Should be
id: 1
Hi, I would like to create my own API of dog images that display the image of the dog, the type of dog and a short description. I have never done this before and would like some advice as where to start please. I want to do it all from scratch so I would like to first create a database of dog images, with the name and description? If so where would I start with making my own db? I have some PSQL experience. So if anyone knows of any good tutorials or have any tips then that would be awesome!
uhh
idk how to ask this
but i have a dns
that im trying to grant access to, in mysql
i know that I can use a wildcard to allow variations of that dns
but, for some reason its the first part of my dns that is change
for context im using aws ec2
ec2-22-33-44-5555.compute-1.amazonaws.com'
so like
ec2-22-33-44-6666. or like ec2-22-33-44-8888.
can i do something like
ec2-22-33-44-%.
i thought that the wild card had to take the place of all the values in between the .
so like 11.22.33.4444, i thought i could only do something like 11.% or 11.22.33.%
or can i do something like
11.2%.33.4444
?
hello
Hello, I'm looking to do a migration with SQLAlchemy and alembic. The migration is actually a data update to a child table (article_version in my sample). I need to update only the latest record for all the items in the articles table.
The table structure is like article and article_version
The idea is not to use a cursor ( I already made this solution but it was not well received )
Any suggestion is well received.
Thanks in advance.
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 69, in gang
testing = str(existing["gang"])
TypeError: 'NoneType' object is not subscriptable
The above exception was the direct cause of the following exception:```
testing = str(existing["gang"])
print(testing)```
should variables in MongoDB (.json database) be short? as i know data is stored in documents, not tables...
like it is preferable to write for example 'l' isntead of 'language'
I have my own SQL server right? I connect to it using a mysql-connector.
I recently made the server.
I know how to Select, Insert, Update, Delete etc.
My question is, how do I make a file where I establish the connection to the server then I write a lot of functions in said file.
And I can import said file to other files to use these functions without needing to reconnect all the time?
languagedata = collectionG.find_one({"_id":1})["language"]
error: KeyError: 'language'
why help
;/
languagedata = collectionG.find({"_id": 1})
for lang in languagedata:
language = lang["language"]
hm
i think this is how it should work if you want to get a key from your collection
what if it doesnt exist
what you exactly trying to do ?
so like for example you want to get 'something' from language ?
i guess that should work
then just print (language) or whatever to display it
oh ok ๐
Thx
btw i wanted to ask @torn sphinx ...
is it fine to store long variables in .json?
sure
are you using a json file as a database ?
there is no difference actually
i mean the difference will take just little bit of space , and not that visual difference
mongo db got like 400mb free space or more lol , dw you will never run out of space
unless you got alot alot of collection
TypeError: string indices must be integer
hm
i still want to keep as less as i can
don't even bother of that
languagedata = x["language"]
TypeError: string indices must be integers
help XD
I am dumb to understand this
did that just came out of the code i gave you ?
yes
so ["language"][x]
It's like doing this,
x = "hello"
print(x['language']) # gives error
print(x[0]) # prints letter h
As the error says you can only use integer to index a string
Your value is in x so what are you even doing there
do you even have the key language on your collection
then why you searching for it
then it would do other thing
oh ok
@haughty ravine it would be very helpful if you can show us your database structure
i removed find_one and the error changed
_id:blablah
thats it lol
so if you have no "language" key how can you find one?
i want so if it doesnt have "language" key then it would create one
?
collectionG.update_one({"_id":1},{"$set":{"language":value}},upsert=True)
but i want to get a language value
if collection.count_document({"_id":1 , "language"}) ==0:
collection.insert_one({"_id":1,"language})
i guess this one mighy work , I don't remember most of it
collectionG.insert_one({"_id":1})
data = collectionG.find_one({"_id":1})["language"]```
but if the object doesn't have a language value how can it return one?
You need to check first do it like this:
collections.find_one({"_id":1},{"language":1,"_id":0})
if this return None it means you don't have any language key
thats what i had already
hmm does it work though?
no
invalid syntax
sorry this will not return None instead it will return you an empty dictionary
if collection.count_document({"_id":1 , "language"}) ==0: syntax error
oh alr
still syntax error
if its empty you can check it by if conditions, and then use the upsert condition if you to update
if collectionG.count_documents({"_id":ctx.guild.id, "language"}) == 0:
collectionG.insert_one({"_id":ctx.guild.id})
data = collectionG.find_one({"_id":ctx.guild.id})["language"]
if languagedata == None:
if language != 'en':
collectionG.insert_one({"_id":ctx.guild.id})
await ctx.send(f'The language has been set to {language}')
return
languagedata = 'en'
if language == languagedata:
await ctx.send('You have the same current language')
return
elif language != languagedata:
if language != 'en':
collectionG.update_one({"_id":ctx.guild.id}, {"$set":{"language":1}})
elif language == 'en':
collectionG.update_one({"_id":ctx.guild.id}, {"$unset":{"language":1}})
await ctx.send(f'The language has been updated to {language}')
return
thats my discord bot
thats why it has ctx.guild.id etc
where is your languagedata variable declared?
?
you are using languagedata but it seems you are storing the dictionary in data variable
yes it would give you the syntax error because it's returning a dictionary in which there is not "language" key but you are trying to access it
data = collectionG.find_one({"_id":ctx.guild.id})["language"]
ig this line is giving you the error?
you have to pass a value to "language"
same reason
what value :/
don't pass language there
what language you are trying to find
it can be anything
only use _id
an exception: KeyError: 'language'
.
languagedata = collectionG.find_one({"_id":ctx.guild.id})["language"]
but what should i use then
if it doesnt have language variable
how do i check it if it doesnt have one
this one
and check if the dictionary is empty or not, if its empty that means you don't have a language key
hm yes i believe lol
ohhh
wait
i think i understood where my mistake is
collections.find_one({"_id":1},{"language":1,"_id":0})
nah
it still shows as "1"
in my case i want to show ru
as russian
or if it is en
then it would be just blank
to keep less data
hm
wait lmao
i found my mistake
lets try again..
if collectionG.count_documents({"_id":ctx.guild.id, "language": "en"}) == 0:
collectionG.insert_one({"_id":ctx.guild.id, "language":"en"})
data = collectionG.find({"_id":ctx.guild.id})
for x in data:
if x["language"] != 'en':
collectionG.insert_one({"_id":ctx.guild.id, "language": "en"})
await ctx.send(f'The language has been set to {language}')
return
elif : x["language"]== 'en'
await ctx.send('You have the same current language')
return
this what i came out with xD
so basically what is does , when it find the language is not set to en
it update it to en , and then send the message
else if it's already set to en it says it's already en
hm
tell me what you trynna do with that code
emm
like i trying to create a command which sets discord bot language
{'language': 'en'}
how do i get en from here?
languagedata = collectionG.find_one({"_id":ctx.guild.id},{"language":language,"_id":0}) gets me {'language': 'en'}
but how do i get en :/
hm
how do i get only language key from this line? cause i get language dictionary which i dont need
oh ok so you want to update the language to the language that the user specified
if they didn't specify it stays as en ?
save it in a variable and use .get("language") on that variable, if it has a language key it will return one
you can also use it like this
var['language']
so if there is no "language" in my collection for this user
that means he has english as default
if it has for example russian
print(var['language'])```
then it puts "ru" to his document
you are the one who sets the language in the first place
so en as default
but if they used the command and specified ru
it get updated to ru
this is what i think it should look like
so for every server you set en as default for the language
best way is to use upsert, it's a one line of code
if they wanted to change it to ru , they just execute the command with specifying ru
yep
languagedata = collectionG.find_one({"_id":ctx.guild.id},{"language":language,"_id":0}).get("language")
print(language)
print(languagedata)
language and languagedata are always the same!
why lol
there are actually no marks in a database
if i say ru in command
languagedata turns ru too
goshh
print(language)
print(languagedata)
if languagedata == None:
languagedata = 'en'
if language == languagedata:
await ctx.send('You have the same current language')
return
this thing always says "You have the same current language"
pika_ is typing...
XD
@client.command()
async def set_language(ctx, language):
( you access to you mongodb)
guild_id = ctx.guild.id
server_language = {"_id": guild_id, "language" : "en"}
if collectionG.count_documents(server_language) ==0:
collectionG.insert_one(server_id)
data =collection.find(server_language)
for x in data:
lang = x["language"]
if lang == language:
return await ctx.send("you already have that language set up")
else:
new_language = language
collection.update_one({"_id": guild_id},{"$set" :{"language": new_language}}, upsert = True)
await ctx.send(f"you set the language to {language}")
this is how it should work i think, if i didn't miss a thing
@haughty ravine
Go, Postgres!!!
