#databases
1 messages · Page 136 of 1
😄
#help-candy i dont want to bother you and tag
but if you see it i would like to get some help
with what make gui?
with what make gui?
@ripe bronze tkinter
Might wanna go to #user-interfaces for docs
ok thx
Traceback (most recent call last):
File "C:\Users\Guilherme\Desktop\devils\devils.py", line 22, in <module>
cred = credentials.Certificate('patch/to/devils-160220-d10d29677e75.json')
File "C:\Users\Guilherme\AppData\Local\Programs\Python\Python37-32\lib\site-packages\firebase_admin\credentials.py", line 82, in __init__
with open(cert) as json_file:
FileNotFoundError: [Errno 2] No such file or directory: 'patch/to/devils-160220-d10d29677e75.json'
does anyone know how to solve this error? I'm trying to use fire base
Hello peeps is there any guide that teaches you how to deploy a ubuntu server with new sql server 2019 DB and to configure the network settings to allow remote connections ?
I tried some guides but remote connections were not possible also I tried those on a windows machine
Also Is tomcat required?
Ping me if reply plz thank you
hi I have a question
I have more than one database, and I have an application that shows these databases, but the name and column names of each database are different, how can I edit my codes according to each database ? here's my code. https://github.com/Furkan-izgi/SATDP
How can I fix when I open those databases ?
in sql lite 3 how can i add list data in a TEXT field or is a different field for it?
you can just dump the list into the text field in string form, and then while retrieving it, you can use json.loads
like for discord suppose this is a list of roles
[<Role id=739748738158821376 name='@everyone'>, <Role id=812635903335202828 name='c'>, <Role id=812635853104349204 name='b'>, <Role id=812635828622852116 name='a'>]
how would i add it in the table?
oh in this case, each element is a discord.Role object
storing it like this is rather wasteful, you just need to store the list of IDs of each role
im a noob ;-; could you elaborate?
you cannot directly store a discord.Role object in the database
its not really a supported datatype
so, you instead store just the role IDs
as you can get back the discord.Role object later, if you know the IDs
oh how would i go about doing that?
sql = """INSERT INTO muted_members_roles(roles, member) VALUES (?, ?)"""
val = (member.roles, member)
cursor.execute(sql, val)
here do i change it to member.roles.id?
you need to do a list comprehension
[role.id for role in member.roles] will give you just the list of IDs
role_ids_list = [role.id for role in member.roles] # list of role IDs
# to store it in the database, cast it to string
str(role_ids_list) -> insert this into db
now as it is a string, when you retrieve it, you can use the json.loads function to get back the original list
ohhh ill try that thanks a lot, so if i understand correctly what this is doing is converting the list to string format so it fits in the TEXT field?
#bot-commands message an example
yep
ohh thanks a lot ill look at the example and give it a try
:D
@burnt turret it worked!! thank you so very much
😄
why am i getting this error
sqlite3.OperationalError: no such column: id
```for
```py
n_sql = 'SELECT rowid FROM muted_members_roles WHERE member = (?)'
n_val = (str(member),)
cursor.execute(n_sql, n_val)
n_res = cursor.fetchone()
await ctx.send(n_res)
cursor.execute('DELETE from muted_members_roles WHERE id = ?', (n_res,))
Hi, is it possible to do this?
await cursor.execute("UPDATE rpg SET (money = money+?, pierre = pierre+?, petrole = petrole+?, xp = xp+?, jetons = jetons+?) WHERE user_id"(money, pierre, petrole, xp, jeton, ctx.author.id,))
Because there is no column id? How about DELETE from muted_members_roles WHERE rowid = ??
any recommendations to make a DB to register the id's and number of warns of each person of a discord?? thx
Hello, is there a way to make global variables? basically variables that can interact with txt files?
Can you describe your case? How is it related with databases?
o ah not exactly sure , I am trying to make variables in this file called server.properties and made a small gui to get the input but I am not sure how to put that data into server.properties other then recreating the file
server.properties is a txt file but different extension
yea
You can use configparser to store your variables in INI format: https://docs.python.org/3/library/configparser.html
k ty
Your welcome
Since days
Can integar column in sqlite3 store float numbers
I don't think so
Actually I think my problem is
AttributeError: 'str' object has no attribute 'execute'
Hard to guess without a code
lmao I got it, I named a variable c like an idiot!
If you have downloaded the source package into your computer, you can use the setup.py as follows: << Steps in a tutorial to use the PostgreSQL db, and I dunno where to put this.
Already installed that library
Yeah, you don't need to do this
Anyone know how to read an image from a message and send it to another channel?
attachment.save attachment.to_file
gg
Any ideas why it says I'm trying to create a user, despite it clearly already existing? https://media.discordapp.net/attachments/723304166902202428/812893381453807626/unknown.png IDENTIFIED BY '[password]' and WITH GRANT OPTION cause a syntax error too
Turns out this is likely caused by another issue. Every time I tried to make a connection to my database for the first time in a session, I'd get an error regarding an invalid authentication plugin or something along those lines, and with PHP a new session seems to be made every time so this meant it was impossible for me to connect from PHP. I found out that this was because for some reason MySQL was using caching_sha2_password for my local users, which was bad and that it should be mysql_native_password and I made that change and then found that nothing could connect to the database Access denied for user 'root'@'localhost' (using password: YES) so assumed it would be a permissions issue which is when I found the above issue. I tried restarting my VPS and now I can't connect to my database at all! Any ideas why? Am I going to have to reinstall and reconfigure MySQL now?
so im using potgreSQL, should i be popSQL for coding or just use the default built in editor?
as a beginner im just look for recommendations
Is there a way that I can download/copy all the data of my ‘economy’ table, reset MySQL and then reinstall the downloaded table?
https://dev.mysql.com/doc/refman/8.0/en/mysqldump.html probably what you're looking for
I've never used this but it looks similar to pgdump at first glance
I am hosting postgresql for my discord bot and should i use aws or gcp or azure as i am using elephantsql website for free plan and it provides these three options.
A quick look at that, I'm assuming I need to be able to login for that, which I seem to be unable to do. Is there a way to get around this?
I don't think it'll make too much of a difference there? They all have loads of server locations so whichever you pick you'll likely get one that's not bad
you will need to login to use that. I know of no way to get the data without logging in, sorry :/
Maybe someone else knows
Oof
hi, in sqlite3, is it possible to choose a column with its number? like, if there are 3 lines and i want the second one?
Choose a column with it's number? Columns have names, why would you be trying to get them by "number"
Or do you mean row?
I've found something called mysqld_safe which allows me to get root access without a password, but I don't seem to be able to use mysqldump using this. Any alternatives I can do from directly inside the mysql terminal?
Never had to find alternative ways to do this :/ sorry
line* sorry
You'd need to have an autoincrementing column for that https://sqlite.org/autoinc.html
Which is better a better PostgreSQL or MySQL?
I have used MySQL but many people say that PostgreSQL is better. Which one should I use? PostgreSQL or MySQL and if I use PostgreSQL is the syntax different or similar to MySQL.
Psql is my favorite
Mysql is a bit different syntax. I think Psql is getting better love/updates and is becoming more common than mysql
Use google trends and check the job boards you care about
Oh! Which is better? In what metric?
Faster? More used? Better icon?
How do I create a db in PostgreSQL
how do i get alias and quote columns based on serials
I want to create multiple things for one single user in my database but I am unsure on how to go about it. For example, if i wanted to keep a record of what rule somebody broke. The first method i've been told to use is to not have a primary key and have multiple rows of the same user but different records. So it would like
id | name | description |
------------------------------
66 | john | broke rule 3 |
66 | john | broke rule 1 |
The other method i've been told to use is use a json string and parse the string information into what I need. So it would look like this:
id | name | description |
----------------------------------------------------------------------------
66 | john | {'record1' : 'broke rule 1'}, {'record2' : 'broke rule 2'} |
Which way would be the better way?
CREATE DATABASE command
Just like that?
CREATE DATABASE dbname creates a database called...dbname
i tried out mysql lite3 yesterday and i wanna know, can it only make tables? if so how different is it from storing data in an excel sheet?
SELECT alias, quotes FROM tablename WHERE serial = .... Whatever condition you want
Thanks a lot
MySQL or sqlite3?
Either ways I'd say using a relational database is much more convenient, as SQL let's you run rather complicated queries easily
@burnt turret Doing this CREATE DATABASE money says invalid syntax
Every SQL query ends with a ;
Actually i was thinking something else i figured it eventually.. Still thanks
I'd recommend you check out the resources I linked earoier
ah
sqllite 3 sorry
also wdym by relational database?
CREATE DATABASE money; Still says invalid syntax
Show your query
Databases like mysql, sqlite all store data in tables - meaning the data have some sort of relationship between them. Hence relational database.
Where are you typing this into
Did I make any sense here 😅
Into the code-
...so show the code
ohhh that makes sense like table: animals have columns for say dogs cats etc hence relational?
This is all I have lmfao
Where are you typing this? In psql?
And importing psycopg2
That obviously will be invalid syntax
You have to tell psycopg2 to execute the statement
That's what you said to do 
You asked "how to create database" - I said how to create database
You didn't tell me that you mean to use python code with psycopg2 to make a database
I typed exactly what you said to type loll
Oh well yes that's what I mean
Well I won't know that without you telling me
Open up psql, login to your root account, and run the query I said
Just put that aside
After doing that, using psycopg2 to connect to the database will be simpler
Wait you can't use the db from the code?
I'd rather have it not be simpler lol
You'll be making the database only once
What does it matter if you do it from the code or from the shell
just open it, and it'll prompt you for your login details
Type in psql into your computers search bar
Nope, not prompting me for login details
Where r they?
Hey @torn sphinx!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
^^ is my error and this is my sqlite3 file:
IF anyone can pls check it would mean alot!
mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'test'@'localhost' (using password: YES)
How do I get access??
Command raised an exception: PendingRollbackError: This Session's transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). Original exception was: (sqlite3.OperationalError) no such table: mutes
[SQL: INSERT INTO mutes ("mutedMemberID", "muterMemberID", "mutedNow", "mutedByCommand", "mutedByReaction", "mutedInChannelID", "messageGotMutedLink", "mutedAt", "reasonMute", "reasonUnmute", "unmuterMemberID", "unmutedAt") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)]
[parameters: (277706835430080512, 555776089524273152, 1, 1, 0, None, None, '2021-02-21 17:02:01.962603', ('Testing', 'db.'), '', None, None)]
(Background on this error at: http://sqlalche.me/e/14/e3q8) (Background on this error at: http://sqlalche.me/e/14/7s2a)```
anyone?
its for sqlalchemy
Is there a dedicated SQL discord server?
no, its a local sqlite file
i make the base class, then the engine, then session maker, then the session
and that happens when i try to add
this is the class:
class MuteEvent(Base):
__tablename__ = 'mutes'
id = Column(Integer, primary_key=True, nullable=False, autoincrement=True)
mutedMemberID = Column(Integer)
muterMemberID = Column(Integer)
mutedNow = Column(Boolean)
mutedByCommand = Column(Boolean)
mutedByReaction = Column(Boolean)
mutedInChannelID = Column(Integer, nullable=True)
messageGotMutedLink = Column(String, nullable=True)
mutedAt = Column(DateTime)
reasonMute = Column(String, nullable=True)
reasonUnmute = Column(String, nullable=True)
unmuterMemberID = Column(Integer, nullable=True)
unmutedAt = Column(DateTime, nullable=True)
def __init__(self, mutedMemberID, muterMemberID, mutedNow, mutedByCommand, mutedByReaction, mutedInChannelID,
messageGotMutedLink, mutedAt, reasonMute='', reasonUnmute='', unmuterMemberID=None, unmutedAt=None):
self.mutedMemberID = mutedMemberID
self.muterMemberID = muterMemberID
self.mutedNow = mutedNow
self.mutedByCommand = mutedByCommand
self.mutedByReaction = mutedByReaction
self.mutedInChannelID = mutedInChannelID
self.messageGotMutedLink = messageGotMutedLink
self.mutedAt = mutedAt
self.reasonMute = reasonMute
self.reasonUnmute = reasonUnmute
self.unmuterMemberID = unmuterMemberID
self.unmutedAt = unmutedAt```
seems like you don't have a column called search_text
https://paste.pythondiscord.com/revucivagu.apache can someone tell me why tkinter crashes when i hit the save button
lemme try googling how to add that maybe that will solve the prob
Hi, is it possible to add a column to an existing table with a default value?
Does anyone know about any good tutorials for using databases with python
Yes. Use the ```sql
ALTER TABLE
also is this normal for a .db file in pycharm
oh how do you open it?
I had this but when I opened it, the first_name and last_name and email etc werent changed
You can download a database browser
Ok thx!
you can use dbeaver
Hey all, I posted a (pretty simple) question in #help-cake and any help would be amazing.
in a
'SELECT FROM WHERE'
how do I make if I need to check more than one column in the where?
basically it's
tag = await conn.fetchval('SELECT tag FROM tags2 WHERE country=$1, nation)
now
tag is a string
tags2 is the table inside the db
country is a string as well
I'd like to add (in the where) to check another column of the table (which is a boolean)
with sqlite how do I make it so that everytime I run the python program it doesn't make a new table
@mighty sun you just comment/delete the code for creating the table.(if you are running using :memory: then it is fine)
if anybody in here could jump into #code-help-voice-text and help me with a pretty simple error I am having that would be amazing
you can join conditions with an AND / OR
WHERE condition1 AND condition2 would mean only rows where both conditions are true are returned
WHERE condition1 OR condition2 would mean rows where either are true are returned
unsure, but sqlite may also let you write queries like CREATE TABLE IF NOT EXISTS
So, perfect for what they wanted
What db do you guys usually use with Django?
does anyone have a good format for a points system for discord.py
One that gives a user a point whenever someone types a certain command
@sterile oracle what you mean good format?
Just an example
Does anyone know if how we can precalculate a value in one column each time a value in another column is inserted/updated ?
i will have the same formula for the calculation, just one variable is the value of other column
@sterile oracle you calculate the points in the command or inside on_command event, and insert or update in database
Would any of you consider this script useful?
https://paste.pythondiscord.com/ifaniyoyoq.py
The main use is to subclass, and make a high level database management class.
For example, here's a script to manage a setting database for guilds:
https://paste.pythondiscord.com/dedijapeqi.py
if i make a psql table with 4 billion rows
but i want to only query the top row/first row in an id index
will it be able to just query the top row super quick from the beginning and not have to go searching through billions of rows to find it?
i'm not actually sure
the _lookup_record() function would work by
_lookup_record(tablename="my_table", expression="id = 1")
making the sql code
SELECT * FROM my_table WHERE id = 1;
i don't actually know much about sql, which is why i made this to make it easier, so i wouldn't be able to answer that
ty
yea not too worried about the py implementation but more just about how i can make queries over 4b records efficient
is there a way to directly check a tab from a db? 
async def find(self, ctx, *, nation: str):
"""Searches for a country and sees if it has missions (+me find Golden Horde)"""
if len(nation) == 3 and nation.isupper():
tag = nation
print(f'Wiki request received! {tag}')
async with self.bot.db.acquire() as conn:
keyword = await conn.fetchval('SELECT country FROM tags2 WHERE tag=$1 AND mission', tag)
nation = keyword
keyword = nation.rstrip().replace(' ', '_')
x = await conn.fetchrow('SELECT one, two, three, four, five, six, seven FROM idea_names WHERE tag=$1', tag)
else:
nation = nation.title()
print(f'Wiki request received! {nation}')
async with self.bot.db.acquire() as conn:
tag = await conn.fetchval('SELECT tag FROM tags2 WHERE country=$1 AND mission', nation)
x = await conn.fetchrow('SELECT one, two, three, four, five, six, seven FROM idea_names WHERE tag=$1', tag)
if tag is None:
await ctx.send('Does your nation have Bielefeld as a name? Neko is sure it doesn\'t exist oAo')
return
now, for now I've put AND mission in the search, and the mission field is a simple true/false stating if the country have/not have ME missions
but in this way if would not really be the best, cause if the country does not have ME mission, it will tell that the country does not exist.
what I was thinking about is an if after the else something like
if mission is False:
await ctx.send('{nation} does not have ME missions')
return
but obviously, "mission" is wrong cause it's undeclared, and I don't recall how to check the field 
this is how the db looks like 
Hello
So I was working on a discord bot which is connected to a async sql offline db
I was wondering if I could create a single connection to the database instead of connecting multiple times in different functions
Sure you can
You could make use of a single connection pool too
Either ways, what you'd do is adding the object to a bot variable - an example is there in the top-most pinned message (it's linked as asyncpg with dpy but the idea is the same) @hollow abyss
You can use DI to have one single connection
I am using asyncsql
What's a DI?
DI? What's that
!pypi asyncsql
what database is this?
Anyways my point stands - what I referred to was an example using asyncpg but the idea is the same, assign the connection object to a bot variable so that it is accessible across all of your bots files
Dependency injection
I have container with DB service and can easily use it in my whole application
!pypi asyncsqlite3
Tf?
I see
hi
the only async sqlite modules I've heard of here are (the more popular) aiosqlite and (the not so common) asqlite
Yeah forgot the name am on mobile. Yes it is aiosqlite
Maybe the complexity di brings might be overkill for their project don’t you think.
Is better to just assign it to a global var like the bot object which the other person said.
Global variables are not good practice
i have this table:
and i wanna save the fullname(2) of all the users that there math class is equal to = yes into a list
called students
by list i mean list in python not in the db ofcourse
SELECT * FROM users WHERE math_class = 'yes'
thats the first line
but how do i save there fullname into list
'
I'm getting a error here :
Print ("hello")
Error: you are too dumb to learn python
Pls help
Someone
Plz
Anyone know how tgo import an outlook calender into python
its : ```py
print("You know python")
#not
Print("I dont know python")
Oh thnx dude I tried that and it worked
nppp
What module are you using for this
Should I store someones discord ID as an int, or can discord IDs be larger than the int type?
Cause I was thinking of storing them as storing as strings and converting them if I need t o
i think it doesn't fit in an INT, i've been using BIGINT
you can store it as strings and convert though
i'm not sure about any performance implications either type has
I'm using SQLite which says bigints are stored as integers so I'll just try it like that
I might just store it as text and convert it to be safe
await con.execute("INSERT INTO persevere(question, answer) VALUES(?, ?)", (question, answer))
why wont this querie run
this querie wont run and doesnt give any feedback
Im not trying it
What feedback do you need
Trying to remove data that has specific string in a column. Currently using panda, cleaned up the code looks like this
import pandas as pd
xl = pd.ExcelFile("finance.xlsx")
df = xl.parse("Excel Output")
df = df.sort_values(by=["Last Name","Event Date"])
df=df.drop_duplicates(subset="User ID",keep="last")
df[df["Event"].str.contains("Hire")==False]
It drops the duplicates, but does not drop rows with "Hire" in the "Event" column
Whats wrong with this code? c.execute("""ALTER TABLE botdata DROP COLUMN accountcreated""")
It says syntax error near "DROP"
hey can someone explain this
DROP TABLE IF EXISTS posts;
CREATE TABLE posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
title TEXT NOT NULL,
content TEXT NOT NULL
);
i haven't used SQL in a while and i'm trying to build a web app off a tutorial but i don't know what it's doing
i dont know what is modle
i use python for coding and i imported mysql-connector
@rain plank can you help me?
Does anybody here know how i can connect to my mongodb thats hosted on my PI from my main computer?
I tried this, but get a connection refused error. this is the IP of my PI
https://cdn.discordapp.com/attachments/244238578400362498/813503876044947546/unknown.png
Make sure that you have open port to connect with MongoDB
Are your Pi and main computer in same network, right?
yea on my lan
how do i open ports?
Do i also have to open them on my main pc, and pi?
or just on my pi?
Raspbian 64bit
https://docs.mongodb.com/manual/tutorial/configure-linux-iptables-firewall/#configure-linux-iptables-firewall-for-mongodb here you have tutorial from MongoDB
ay ty
What does this mean?
sqlalchemy.exc.OperationalError: (MySQLdb._exceptions.OperationalError) (1241, 'Operand should contain 1 column(s)')
[SQL: UPDATE items SET sizes=%s WHERE items.supreme_id = %s]
[parameters: ((['N/A'], 29528), (['129', '139', '149'], 29624))]
Can you share more code?
hi
that is also unknown
Are you sure? https://serverfault.com/a/563036/276243
Sure
This is my model
class Item(Base):
__tablename__ = 'items'
supreme_id = Column(Integer, primary_key=True)
name = Column(String(200))
image = Column(String(200))
category = Column(String(200))
in_stock = Column(Boolean)
last_time_in_stock = Column(BigInteger)
sizes = Column(String(200))
color = Column(String(200))
price = Column(Integer)
def __int__(self, name: str, image: str, category: str, supreme_id: int, in_stock: bool, last_time_in_stock: int, sizes, color: str, price: int):
self.name = name
self.image = image
self.category = category
self.supreme_id = supreme_id
self.in_stock = in_stock
self.last_time_in_stock = last_time_in_stock
if isinstance(sizes, str):
self.sizes = json.loads(sizes)
else:
self.sizes = sizes
self.color = color
self.price = price
def create(self) -> None:
if isinstance(self.sizes, list):
self.sizes = json.dumps(self.sizes)
session.add(self)
session.commit()
if isinstance(self.sizes, str):
self.sizes = json.loads(self.sizes)
def update(self) -> None:
if isinstance(self.sizes, list):
self.sizes = json.dumps(self.sizes)
print(f'{self.sizes} - [{type(self.sizes)}]')
session.add(self)
session.commit()
if isinstance(self.sizes, str):
self.sizes = json.loads(self.sizes)
And I am getting errors in create and update
sizes is a list
That I serialize
@prisma girder
What this print print(f'{self.sizes} - [{type(self.sizes)}]') returns?
https://cdn.discordapp.com/attachments/244238578400362498/813513363283378227/unknown.png
I tried this before to open the ports needed to connect remotely to my mongodb database
however when i did this it meant i was no longer able to connect via VNC viewer, or winSCP
Anybody have any idea why? As this is the only method i know on how to open ports
You can try ufw, I don't know what is wrong
Stange... What is your session?
I don't want to do this again unless i have some form of idea of why it happened, as everytime i try it i have to reset my PI to be able to connect to it again
Wdym
You have session.add(self) and session.commit() so from where session comes from?
Oh
Session = sessionmaker(bind=engine, autoflush=False, autocommit=False)
session = Session()
global session
I am using async
async def main():
async with ClientSession() as session:
while True:
release_data = await get_latest_releases(session)
await run_jobs(item_handler, release_data, session, max_workers=5)
async def item_handler(data, session):
# try:
proxy = await get_proxy()
user_agent = UserAgent(cache=False)
headers = {'User-Agent': user_agent.random}
response = await session.get(f'https://www.supremenewyork.com/shop/{data["item_id"]}.json', proxy=f'http://{proxy}',
headers=headers)
response.raise_for_status()
response = await response.json()
for style in response['styles']:
start = int(time.time())
sizes = []
for size in style['sizes']:
if int(size['stock_level']) > 0:
sizes.append(size['name'])
it = Item.get(style['id'])
print(type(sizes))
if len(sizes) > 0:
if not it:
if sizes == "N/A":
sizes = json.dumps(["N/A"])
item = Item(name=f"{data['item_name']} {style['name']}", image=style['image_url_hi'],
category=data["category"], supreme_id=style['id'], in_stock=True,
last_time_in_stock=int(time.time()), sizes=sizes, color=style['name'])
item.create()
print(f'[{item.name}] [IN STOCK] [Sending Webhook]')
await Item.send_notification(session=session, object=item, start=start)
else:
if it.in_stock and sizes != it.sizes:
it.in_stock = True
it.last_time_in_stock = int(time.time())
if sizes == "N/A":
sizes = json.dumps(["N/A"])
it.sizes = sizes
it.update()
print(f'[{it.name}] [IN STOCK] [Sending Webhook]')
await Item.send_notification(session=session, object=it, start=start)
else:
if not it:
item = Item(name=f"{data['item_name']} {style['name']}", image=style['image_url_hi'],
category=data["category"], supreme_id=style['id'], in_stock=False,
last_time_in_stock=0, sizes="[]")
item.create()
print(f'[{item.name}] [OOS][0]')
else:
it.in_stock = False
it.sizes = []
it.update()
print(f'[{it.name}] [OOS][1]')
So basically item_handler is the one that makes the error
@prisma girder
Hmm, what is type of supreme_id?
I am curious about your parameters: [parameters: ((['N/A'], 29528), (['129', '139', '149'], 29624))]
I am not master of sqlalchemy but it looks like you pass tuple of tuples into UPDATE
However I may be wrong
Hmm
Hard to say for me without ability to debug
I have been trying to fix this for the best 5 hours haha
You can also use pickle column type to store Python objects as blobs
Well I think the problem occurs when creating the object
and I can't leave the sizes field blank
Have you tried to catch this object with sqlalchemy events?
It can be helpful
How about bindIpAll?
How do I select an entire column and get all the queries in it using sqlite
I can connect via mongo compass now
thank you everybody for all the stuff yu helped me with 🙂
@prisma girder This is what I see right before the error
2021-02-22 23:24:48,644 INFO sqlalchemy.engine.base.Engine SELECT items.supreme_id AS items_supreme_id, items.name AS items_name, items.image AS items_image, items.category AS items_category, items.in_stock AS items_in_stock, items.last_time_in_stock AS items_last_time_in_stock, items.sizes AS items_sizes, items.color AS items_color, items.price AS items_price
FROM items
WHERE items.supreme_id = %s
LIMIT %s
2021-02-22 23:24:48,644 INFO sqlalchemy.engine.base.Engine (29528, 1)
2021-02-22 23:24:48,827 INFO sqlalchemy.engine.base.Engine UPDATE items SET sizes=%s WHERE items.supreme_id = %s
2021-02-22 23:24:48,827 INFO sqlalchemy.engine.base.Engine (['129', '139', '149'], 29624)
2021-02-22 23:24:48,981 INFO sqlalchemy.engine.base.Engine ROLLBACK
Hey @solemn ridge!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
This ['129', '139', '149'] doesn't look like str but list[str] for me 
How about this - dump this field always? No if isinstance(self.sizes, list): because maybe it's iterable?
I am guessing now
But the thing
is
def create(self) -> None:
print(type(self.sizes))
if isinstance(self.sizes, list):
self.sizes = json.dumps(self.sizes)
session.add(self)
session.commit()
if isinstance(self.sizes, str):
self.sizes = json.loads(self.sizes)
This prints <class 'str'>
Are you invoking item_handler several times? I mean - can be here hazard?
Output of this:
def create(self) -> None:
print(self.sizes,type(self.sizes))
if isinstance(self.sizes, list):
self.sizes = json.dumps(self.sizes)
session.add(self)
session.commit()
if isinstance(self.sizes, str):
self.sizes = json.loads(self.sizes)
["129", "139", "149"] <class 'str'>
Yes I am
When multiple objects is trying to call session.commit()
A lot of times, asynchronously
That was my initial though
I recommend to add some Lock
Couldn't find how to fix it
I don't know anything about threading-safety for sessions
Hmm
I actually didn't think
of a lock mechanism
Give me a second to adjust my code
Right
It did not work..
Does anyone know why this Sqlite3 file wont work in pycharm:
Hey @torn sphinx!
It looks like you tried to attach file type(s) that we do not allow (.sqlite3). We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .psd, .ai, .aep, .xcf, .mp3, .wav, .ogg, .webm, .webp, .flac, .afdesign, .m4a, .csv.
Feel free to ask in #community-meta if you think this is a mistake.
Hey @torn sphinx!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
^ this works on repl.it but not on terminal
^ this one works with python but i have to add text to it and i want to make the 1st link work
Greetings, given the following sql table sample
declare @Table2 table(invoice int, amount int)
insert into @Table2
select 1234, 25 union
select 1234, 75 union
select 1234, 100 union
select 1234, 175 union
select 1234, 180 union
select 1234, 100
How can I write some python script to grab me any combination that produces 500? Gracias
on the amount column that is. thanks
how can I get the data from mysql's server, then I mapping into pipeline? is there anyone can teach me?
i have this table:
i want to save to var called list_of_names every fullname of someone who is math_class = yes
so i did
SELECT FROM users WHERE math_class = 'yes'
and i get a list of everything
but i want only fullname
and also to save it to var
im using mysql-connector and python ofcourse
SELECT fullname FROM users WHERE math_class = 'yes'
and how do i save it to list
how were you doing it before?
i didnt
like now im working on msg system
till now i had only login,register system
which is other commands
for sql commands i did
handler.execute(SQL HERE)
I think I've discussed fetch methods with you before?
list_var = cursor.fetchall() after your .execute will assign it to list_var (i've used cursor as an example, use your actual cursor variable there)
command will be:
handler.execute('SELECT fullname FROM users WHERE math_class = "yes"')
list_of_fullnames = handler.fetchall()
if i understood?
yep
than list_of_fullnames will be string i guess right
yeah nice
how do i check the current class
i need to check wheater math_class = yes or english class = yes or arabic class = yes
how i would do it?
wdym by current class though
what you typed here will work lmao
no but now i have another question
so like teacher logs in called eti and in the db her math_class = yes, english_class = no, arabic_class = no
ok?
now i want to check what class she teaches then save the fullname of all the students that learn math
but i have an idea i will try thank you
error
you need to specify a column that you want to retrieve
if you want all columns that's SELECT * ...
else
like this
Have you tried to add event listeners and check what is going on?
def login_screen_teacher():
# screen.destroy()
global screen3
screen3 = Tk()
screen3.title('Teacher Login')
admin_login_text = Label(screen3, text="Teacher Login", bg="grey", fg='white', width="20", height="1", font=("Calibri", 13))
admin_login_text.grid(row=0,column=1,sticky=W,pady=0)
label1 = Label(screen3, text="Username :")
label2 = Label(screen3, text="Password :")
label1.grid(row=1, column=0, sticky=W, pady=2)
label2.grid(row=2, column=0, sticky=W, pady=2)
global username_entry2
global password_entry2
global Hide_button2
global Show_button2
username_entry2 = Entry(screen3,width='20')
password_entry2 = Entry(screen3,width='20')
username_entry2.grid(row=1, column=1, pady=2)
password_entry2.grid(row=2, column=1, pady=2)
password_entry2.config(show="*")
login = Button(screen3, text='Login', command=check_login_info_teacher)
login.grid(row=3, column=2, pady=2)
Back = Button(screen3, text='Back',command=back_from_teacher_login)
Back.grid(row=3,column=0,pady=2)
Show_button2 = Button(screen3, width=4, text='Show', command=show_password_entry2)
Show_button2.grid(row=2, column=2, pady=1)
Hide_button2 = Button(screen3, width=4, text='Hide', command=hide_password_entry2)
screen3.mainloop()
def check_login_info_teacher():
username = username_entry2.get()
password = password_entry2.get()
query_vals = (username, password, 'teacher')
handler.execute("SELECT FROM users WHERE username = %s AND password = %s AND role = %s", query_vals)
if handler.rowcount <= 0:
username_entry2.delete(0,END)
password_entry2.delete(0, END)
teacher_login_failed = Label(screen3, text="wrong credentials", bg="yellow", fg='black', width="15", height="1", font=("Calibri", 10))
teacher_login_failed.grid(row=3,column=1,pady=2)
else:
teacher_sesh()
and i get this error
thats realy weird
already answered
all good 😄
def send_msg_to_student():
screen7.destroy()
global screen9
screen9 = Tk()
screen9.title('Send new msg')
screen9.geometry('400x150')
screen9.resizable(False, False)
add_new_user_text = Label(screen9, text="Send new msg", bg="grey", fg='white', width="24", height="1",font=("Calibri", 20)).place(x=0,y=0)
label = Label(screen9, text="Message content:").place(x=0,y=45)
global msg_inserted
msg_inserted = Entry(screen9, width='20')
msg_inserted.place(x=100,y=45)
global drop_menu1
global var1
var1 = 'hello'
var1 = StringVar()
user = (username,)
print(user)
handler.execute('SELECT math_class from users WHERE username = %s', user)
math_value = handler.fetchall()
handler.execute('SELECT arabic_class from users WHERE username = %s', user)
arabic_value = handler.fetchall()
handler.execute('SELECT english_class from users WHERE username = %s', user)
english_value = handler.fetchall()
if math_value == 'yes':
handler.execute('SELECT fullname FROM users WHERE math_class = "yes"')
list_of_fullnames = handler.fetchall()
elif english_value == 'yes':
handler.execute('SELECT fullname FROM users WHERE english_value = "yes"')
list_of_fullnames = handler.fetchall()
elif arabic_value == 'yes':
handler.execute('SELECT fullname FROM users WHERE arabic_class = "yes"')
list_of_fullnames = handler.fetchall()
print(list_of_fullnames)
i get this printed
this is my db
shouldnt i get list_of_fullnames printed
including eytam laytter
?
@burnt turret
i got this error
im getting this error i dont know whats wronghttps://gyazo.com/2feebde08f28adb700bbe0545c4fa409
can anyone say how to get mongodb uri and databse?
Hi,
I have mysql installed. I was working on my pc and suddenly mysql console opened itself and said installing packages and then it closed, all by itself. What happened? Is there a virus on my computer?
what is wrong with this code, it is giving me an error: c.execute("""UPDATE botdata SET cash =?, inventory =? WHERE userID =?""", (usercash, userinventory, authorname,))
try using %s instead of ?
I bet you can
well
Hello I am a complete beginner. I've been trying to solve a very simple problem for several hours now, but I can't. I need a script that connects me to a MYSQL DB. Then I want to update the content of a variable and then output the variable again. I know it's a very simple problem, but I still ask for your help.
you should consider going to AVAILABLE HELP CHANNELS
Thanks
I just wanna note that the pinned resource https://sqlbolt.com/ is pretty helpful, I'm using it to learn SQL now
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
hey
i have stored to my json file some emojis i want to use
and as i try to use
await msg.add_reaction(data['types'][i]['emoji'])
i get this error
Command raised an exception: UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 169: character maps to <undefined>
any idea?
help
raise OperationalError(2003,
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1'")
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001CE2F508EE0>
I use the server from another device on the same network
@torn sphinx 127.0.0.1 refers to the machine you're currently on. On each device it will point only to itself.
You need to open the database connection on a different IP address -- the one that other devices on the network can see. I'm not sure exactly how to find it out, but ifconfig should help.
How do I link my python code to my MySQL data base?
for postgres, how would i get all info from a column from a table?
Hello, I have a SQL question: Output the difference in age between each teacher and the next oldest teacher at each school.
Can anyone help?
Hello where do i start with python databases? Videos preferred.
(Yes I'm a total noob)
SELECT columnname FROM tablename;
!pypi mysql-connector-python
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
conn = sqlite3.connect('test.db')
print("Opened database successfully")
Module 'sqlite3' has no 'connect' memberpylint(no-member)'
Can someone help me to fix this problem?
can anyone help me with this kinda of error "snowflake.connector.errors.ProgrammingError: 001003 (42000): SQL compilation error:
syntax error line 1 at position 39 unexpected '<EOF>'."?
Ok thk
import os
import pandas as pd
import snowflake.connector as snow
from snowflake.connector.pandas_tools import write_pandas
#setup and connect
conn = snow.connect(user="<user>", password="<passs>",account="<somestuff>")
cur = conn.cursor()
sql = "USE ROLE SYSADMIN"
cur.execute(sql)
sql = """CREATE WAREHOUSE IF NOT EXISTS SAMPLE_WH
WITH WAREHOUSE_SIZE= XSMALL
AUTO_SUSPEND = 180
AUTO_RESUME = TRUE
INITIALLY_SUSPENDED=TRUE"""
cur.execute(sql)
sql = "USE WAREHOUSE SAMPLE_WH"
cur.execute(sql)
sql = "CREATE DATABASE IF NOT EXISTS SAMPLE_DB"
cur.execute(sql)
sql = "USE DATABASE SAMPLE_DB"
cur.execute(sql)
sql = "CREATE SCHEMA IF NOT EXISTS SAMPLE_SCHEMA" #default schema name is public
cur.execute(sql)
sql = "USE SCHEMA SAMPLE_SCHEMA"
cur.execute(sql)
sql = """CREATE TABLE IF NOT EXISTS SAMPLE_TABLE(
first_name STRING,
last_name STRING,
email STRING,
address STRING,
city STRING)"""
cur.execute(sql)
cur = conn.cursor()
upload data from dataframe
csv_path = r"C:\temp\sample_data.csv"
delimiter = ","
df = pd.read_csv('C:\temp\sample_data.csv')
df = df.T
df = df.drop_duplicates()
df = df.T
df = df.T.drop_duplicates().T
write_pandas(conn, df, "SAMPLE_TABLE")
cur = conn.cursor()
sql = "ALTER WAREHOUSE SAMPLE_WH SUSPEND"
cur.execute(sql)
cur.close()
conn.close()
Ok and can you send the full error?
so what im tryna do is read a csv file using pand and then insert into snowflake db
oh ok
So send the full error message
Traceback (most recent call last):
File "c:\Users\Sanj\Documents\VSCode WorkSpace\WorkSpace_python\Data Warehouse\sf_script.py", line 52, in <module>
return _read(filepath_or_buffer, kwds)
File "C:\Python38\lib\site-packages\pandas\io\parsers.py", line 454, in _read
parser = TextFileReader(fp_or_buf, **kwds)
File "C:\Python38\lib\site-packages\pandas\io\parsers.py", line 948, in __init__
self._make_engine(self.engine)
File "C:\Python38\lib\site-packages\pandas\io\parsers.py", line 1180, in _make_engine
self._engine = CParserWrapper(self.f, **self.options)
File "C:\Python38\lib\site-packages\pandas\io\parsers.py", line 2010, in __init__
self._reader = parsers.TextReader(src, **kwds)
File "pandas\_libs\parsers.pyx", line 382, in pandas._libs.parsers.TextReader.__cinit__
File "pandas\_libs\parsers.pyx", line 674, in pandas._libs.parsers.TextReader._setup_parser_source
OSError: [Errno 22] Invalid argument: 'C:\temp\\sample_data.csv'
get different error when i did
Oh wait its not
df = pd.read_csv(csv_path)
try this code
in replacement of
df = pd.read_csv('C:\temp\sample_data.csv')
Traceback (most recent call last):
File "c:\Users\Sanj\Documents\VSCode WorkSpace\WorkSpace_python\Data Warehouse\sf_script.py", line 59, in <module>
write_pandas(conn, df, "SAMPLE_TABLE")
File "C:\Python38\lib\site-packages\snowflake\connector\pandas_tools.py", line 159, in write_pandas
copy_results = cursor.execute(copy_into_sql, _is_internal=True).fetchall()
File "C:\Python38\lib\site-packages\snowflake\connector\cursor.py", line 614, in execute
Error.errorhandler_wrapper(self.connection, self,
File "C:\Python38\lib\site-packages\snowflake\connector\errors.py", line 224, in errorhandler_wrapper
cursor.errorhandler(connection, cursor, error_class, error_value)
File "C:\Python38\lib\site-packages\snowflake\connector\errors.py", line 179, in default_errorhandler
raise error_class(
snowflake.connector.errors.ProgrammingError: 000904 (42000): SQL compilation error: error line 1 at position 87
invalid identifier '"Nyssa"
Is there something broken in your csv file?
i dont think so lemme try other csv just in case
nope same error = invalid identifier '"<new csv file first word/character>"
mt=> UPDATE config SET announcementchannel = 0;
UPDATE 0
mt=> SELECT * FROM config;
announcementchannel
---------------------
(0 rows)
mt=> UPDATE config SET announcementchannel = 0 WHERE NULL;
UPDATE 0
mt=>```
Huh.
I cannot update announcementchannel.
There has to be some rows for you to update in the first place
Oh true lmao.
hi guys
anyone here familiar with pyrebase ?
why is sqlite3 better than json? anyone knows?
What do you mean?
because json is stored in a human readable format and that makes it very inefficient
okay
you need be more specific. in which context do you ask this question?
anyone have experience with pandas dataframe?
uhh
i see some people say that using json isnt a good choice with discord bots
they recommended a database
JSON is nice format to store configuration or exchange data
gotten to a point where I store a variable as df = pd.DataFrame(values_input[1:], columns=values_input[0])
how do i read it??
@prisma girder yeah but the questions they answered are about like economy system instead of storing configs
If you will be changing the data then use database
If data does not change or very less it’ll be changed then json is ok
Im using sqlite and i want to delete a colum choosen by a command in my table
Umm I don’t think is a good idea to allow users to delete columns from a command
Do you mean row?
Hey all. I am using MongoDB and I am reading their notes and instructions, and even copying and pasting, but I just get syntax errors.
I am trying to count the numbers of entries in an array in a loop of a collection.
I have a collection with questions in it, and each question has two sets of answers, let's say the collection question has two arrays:
array1: Array 0: Object 1: Object 2: Object
and:
array2: Array 0: Object
And then there's another 20 of these to loop through (let's say).
Now I want to rank by the number of entries in array1 + array2
guys i have a question which is related to discord.py and databases but discord.py channel ignored me so here i am
you know how almost everything in discord bot should done asynchronously right?
so will i have to retrieve data from my db asynchrronously too?
There are async driver modules for databases
For example, sqlite has the aiosqlite module, postgres has asyncpg, mysql has aiomysql
these modules do the database interactions also asynchronously @green parcel
How do I have diffrent guilds have diffrent prefixes?
`test = input('What ur name?\nMy name is ')
print ('SUCCESS')
print (' ')
print (' ')
testyears = input('How old are you\nI am ')
print ('SUCCESS')
print (' ')
print (' ')
testweight = input('How many do you weigh?\nI weigh ')
print ('SUCCESS')
print (' ')
print (' ')
print (' ')
print ('Thanks for registering, bye')`
hey guys how would you create a login system w SQL
i have the login page HTML done
i saw something that said use SQL and php
@burnt turret how do I create a file and a table with postgresql?
A file?
yes
postgres isn't a file based database like sqlite
You install postgresql server
nice pfp btw
haha thanks
:notlikeduck:
link?
Quick, I should be asleep now
If you just need it sorted you should be using ORDER BY
Killer - 30
anand - 29
godly - 14
random - 5
how could i achieve this
steam is the name and the numbers is also steam it counts how many times he got it.
hey guys
what's the difference between mysql and sqllite3
i used sqllite3 like once
i didn't ghost ping
Not you, killer
oh ok
yes
so should i use sqllite 3 to create a database for login users or mysql
The main difference is sqlite is file based, but MySQL is server based (you won't be having a file for a database)
You can use either
Sqlite works fine for small projects
well that's what this app is gonna be so
use sqlite3
ok great thanks
SELECT steam, count(*) as num FROM tablename GROUP BY steam ORDER BY num DESC
I think?
i will be back w questions
you definitely should they will ask you in interviews
🕯️
yeah they went all out on me in one interview
but seriously sqllite3 is like key for data science
so intense its like theyre interviewing for a full time
i will get to it soon
its in the next module in my learning plan
Hi friends! As promised, here is a data science SQL interview question done from beginning to end in real interview style. I also go through how to check your work using SQL Fiddle. This is how I practiced every single mock interview for my own FANG data science interview. I'll also link it below so please check out that video for context if you...
this woman taught herself SQL for the DS interview so
i don't wanna get cancelled idk if chick is derogotary now
Does someone know how to count how many items are in an array in a for loop containing these arrays? I am using MongoDB and have tried reading their documentation but it just isn't working.
lol ik i watch her. she did a video explaining how she learned sql in 11 days

crazy shit
oh no i spend a lot of time screwing around
esp in DS where theres infinite things to learn
like being on this server and talking to people

although at the breakneck pace i'm going at it looks like i'm a faangophile
youre still young so you still have time
pls there are 15 year olds on this server who can code better than us
also talking on this server helps you get information passively
dude the server owner hasnt even graduated college yet
hey i prefer talking to you than my introvert high school friends so
and his portfolio is ridic
yes
oh wait hes about to start uni
aka college

hes doing his "A-levels"
which is like the UK equivalent of an optional 13th grade for taking super exams or something

that was my impression which is probably wrong

do you know what it is @keen spoke
yeah i have some friends in UK who are doing that

damn geniuses
those people can do hard leetcode questions by blinking
i wish i were that good
i don't have to be that good
hey guys
if i want to use sqlalchemy
do i have to do pip install sqlalchemy first?
stupid question but i did it
Unable to import 'flask_sqlalchemy'pylint(import-error)
what the hell does that mean
why won't it let me use sqlalchemy
i did pip install flask_sqlalchemy and it said it already existed?
You need to install flask-sqlalchemy to use it
yeah so i did pip install flask_sqlalchemy
and it installed
but it still won't work
Errors?
Show your import statement
Their docs
I dont have a link handy
Yea
They have small tutorials and code snippets for how to connect to the db
And how to do queries
You'll also want to check pymongo
What is that?
Python package for connecting to mongodbs
basically just doxxed myself but that's ok
Whats that
oh my bad
Thats just the terminal
it's from this tutorial if that helps
ModuleNotFoundError: No module named 'flask_sqlalchemy'
Vscode right?
yes
Open the terminal in it and then the python interpreter
The integrated terminal
bash: python3: command not found
Whats the command for python then
Replace that into python3
py3 maybe?
py
Idk
Wait, i made an account and started a cluster
idk either
What next?
How can i cinnect the python file to the database
FLASK_APP=app, FLASK_ENV=development, flask run
I use VSCummnity
it might be py
also should i be using quotes like this "from flask_sqlalchemy import SQLAlchemy" @upper juniper
nope py doesn't work either
Ok anyway just do pip show flask_sqlalchemy
nothing happened
Then you dont have it installed
but i did install it
?
Do you have a venv
no
Go to your terminal and do pip freeze | grep "flask"
ok i did pip install flask_sqlalchemy in the integrated terminal
And check there
and one of the red squigglies went away
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint)
# blueprint for non-auth parts of app
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
return app
but now these froms have squigglies
i don't get why
Unable to import 'Web App Drawing 2.auth'pylint(import-error)
I would personally use from project.filename import function instead of that
ok let's try that
Whats your project called
Web App Drawing 2
from Web App Drawing 2._init_py import auth as auth blue_print?
no that doesn't work
Idk, something shorter and without spaces?
Alright whatever, from .auth import the_blueprint
nope still a squiggly under from
But does it work
?
Did you follow the tutorials?
All of them are about atlas something
Bruh, replace the variable to whatever the blueprint is called
Atlas is cloud mongodb
And you can also setup a local instance
from .auth import the_blueprint
app.register_blueprint(the_blueprint)
# blueprint for non-auth parts of app
from .main import main_blueprint
app.register_blueprint(main_blueprint)
return app
ok but the "from" for both are red underlined
yeah i took it from the tutorial
Show me
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
# init SQLAlchemy so we can use it later in our models
db = SQLAlchemy()
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret-key-goes-here'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
db.init_app(app)
# blueprint for auth routes in our app
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint)
# blueprint for non-auth parts of app
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
return app
this is the tutorial's code
Show me the auth file
They all about atlas something
from flask import Blueprint
from . import db
auth = Blueprint('auth', __name__)
@auth.route('/login')
def login():
return 'Login'
@auth.route('/signup')
def signup():
return 'Signup'
@auth.route('/logout')
def logout():
return 'Logout'
oh is this bc i didn't actually go that far in the tutorial
omg i feel stupid
Wait MongoDB is json?
Its json-like
What is all that?
I don't understand it
They just shows commands
use myNewDB
db.myNewCollection1.insertOne( { x: 1 } )```
Where do i use this?
db.myNewCollection2.insertOne( { x: 1 } )
db.myNewCollection3.createIndex( { y: 1 } )```or that
donno
Those arent python commands
Just setup the db and then read the pymongo docs
To interact with it using python
And this is what i pressed
Anyone? help?
How can i get the database name for this:
>>> import pymongo
>>> client = pymongo.MongoClient("localhost", 27017)
>>> db = client.test
>>> db.name
u'test'
>>> db.my_collection```
idk mongo db so i can't help lmao
Yeah no prob
maybe i will learn mongodb after learning mysql
i need one non-sql language on the bucketlist
and i think that one is the most popular

I need someone that knows
Hi all,
I hope it's the right place to ask this but I hoped to have a short chat about databases for social media based apps where you would store text and images in specific categories for example.
The data is highly secret, how do platforms like facebook do it to prevent sql injection attacks?
Do they make a separate database for each user?
I only have experience with rowbased sql databases, so can you maybe give me a direction where to look for my answer?
hi, is it possible to do this? I want result to be a list where each element is an int
await cursor.execute("SELECT * FROM user_id")
result = await cursor.fetchone()
result = int(str(result))
well its not possible like that no
because result is either None or a tuple
if all the columns in the db are integers then the values in the tuple will be ints already
but, it is int, but it returns me tuples....
wait i try something
because you're selecting all the columns...
well, you're selecting every row from the table user_id
oh, ok, so the person was wrong
so how can i fetch all values of a column?
@brazen charm pls 
Perhaps
Thx lol
Hum, no sorry it's not
Using SQLITE WHERE clauses:
I have a database with each row storing 6 values. I want to select rows where x+ of the values are equal to a certain number. How do do this?
Example with 3 values instead of 6, and x=2
rowid value_a value_b value_c
1 3 1 0
2 2 3 3
3 2 2 2
Then I want all rows where there are 2+ 2s in value_a, value_b, and value_c (result would be row 3 only)
Something like SELECT * WHERE (value_a,value_b,value_c).count(2) >= 2. Any ideas?
Specific to my actual needs it would be (a,b,c,d,e,f).count(2) >= x
how do I create and setup a table with sqyncpg?
Hey, I recently switched over from sqlite3 to aiosqlite and sadly now all my records are returning none. Can anyone help me out with this?
async def record(self, command, *values):
await self.cur.execute(command, tuple(values))
return await self.cur.fetchone()
then when I call record,
with my queries,
for example
eyes = await bot.record("""
SELECT eyecount FROM users WHERE id = ? AND server = ?
""", user.id, ctx.guild.id)
I get None
it connects to the database with path "db."
@tacit umbra idk what that means
Why not?
why is installing mysql such a process
keeps giving me errors
gonna try to downgrade

So how do i connect between mongoDB cluster and discord.py file?
wheres the problem with this?
new_user_id = str(member.id)
f = open('D:\\Python\\Scripts\\DiscordBots\\Ice Bot\\U$3R$.json','r')
usersJs = f.read()
f.close()
UsersJS = json.loads(usersJs)
UsersJS[f"{new_user_id}"] = {"warns":0, "warnsInfo":["None"]}
UpdatedUsersJS = json.dumps(UsersJS, indent = 1)
f = open('D:\\Python\\Scripts\\DiscordBots\\Ice Bot\\U$3R$.json','w')
print(UpdatedUsersJS)
usersJs = f.write(UpdatedUsersJS)
f.close()
the .json file
{
"69903921317150735":{
"warns":0,
"warnsInfo":["None"]
},
"664179343043461141":{
"warns":0,
"warnsInfo":["None"]
}
}
this is the displayed error
Ignoring exception in on_member_join
Traceback (most recent call last):
File "C:\Users\Jose Manuel\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "d:\Python\Scripts\DiscordBots\Ice Bot\main.py", line 94, in on_member_join
UsersJS = json.loads(usersJs)
File "C:\Users\Jose Manuel\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\Jose Manuel\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\Jose Manuel\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ':' delimiter: line 2 column 22 (char 23)
Anyone?
MongoDB has a native Python driver, PyMongo, and a team of Driver engineers dedicated to making the driver fit to the Python community’s needs. In this article, which is aimed at Python developers who are new to MongoDB, you will learn how to create a free hosted MongoDB database, install PyMongo, the Python Driver, connect to MongoDB and more.
Is it about this atlas or without?
wheres the problem with this?
new_user_id = str(member.id)
f = open('D:\\Python\\Scripts\\DiscordBots\\Ice Bot\\U$3R$.json','r')
usersJs = f.read()
f.close()
UsersJS = json.loads(usersJs)
UsersJS[f"{new_user_id}"] = {"warns":0, "warnsInfo":["None"]}
UpdatedUsersJS = json.dumps(UsersJS, indent = 1)
f = open('D:\\Python\\Scripts\\DiscordBots\\Ice Bot\\U$3R$.json','w')
print(UpdatedUsersJS)
usersJs = f.write(UpdatedUsersJS)
f.close()
the .json file
{
"69903921317150735":{
"warns":0,
"warnsInfo":["None"]
},
"664179343043461141":{
"warns":0,
"warnsInfo":["None"]
}
}
this is the displayed error
Ignoring exception in on_member_join
Traceback (most recent call last):
File "C:\Users\Jose Manuel\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "d:\Python\Scripts\DiscordBots\Ice Bot\main.py", line 94, in on_member_join
UsersJS = json.loads(usersJs)
File "C:\Users\Jose Manuel\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\Jose Manuel\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\Jose Manuel\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ':' delimiter: line 2 column 22 (char 23)
Which atlas?
MongoDB Atlas
Oh no, sorry, my mistake... I thought that you want to connect with your cluster
Does anyone here know mongo because I need some quick help
How would I insert a list into mongo await warnsys.insertone({'id': member.id, 'guild': ctx.guild.id, 'warns': []})
doing [] just makes the value of warns null
I don't want this atlas
I went on the website and opened a cluster
So i want some guide without this atlas thing, is it it?
Anyone?
Have you checked my link?
Not yet
So maybe you should check it before asking "Anyone?"?
Maybe it's an answer for your question
Yeah I'm sorry
I look into it in a few minutes
I just want to know if it is what i need
why do you say "i dont want this atlas" though?
it is mongodb's cloud hosted database as a service option
Because I was told i don't need to download this and it is better not to
So what is the difference?
you don't have to install anything, it runs on the cloud
hence, cloud-hosted
using it would be pretty similar to using a database that was hosted locally on your computer - you can follow the link that the other person sent most likely
atlas's official documentation is pretty good too https://docs.atlas.mongodb.com/getting-started/
So the atlas is for multiple servers?
I don't understand what you mean by that
Why is it better to use the atlas than the normal cluster?
what do you mean by "normal cluster"? you are using a cluster on atlas
how do I make a database column that adds together what is in 2 other columns? example:
# these are columns in my db
bank = 60
wallet = 70
networth = 130 # calculated from bank + wallet
you can do that in your query like;
SELECT bank, wallet, bank + wallet AS networth FROM tablename;
ah okay thanks
Cluster from the website
the website you're using is atlas
the service that is providing you the cluster online is what is called mongodb atlas
yes
I don't know of any other cloud-hosted cluster solution for mongodb at least
so most likely yes
yes
Oh perfect
@burnt turret so would this be correct? SELECT * FROM economy ORDER BY bank + wallet AS networth DESC
Than how can i link the .py file to it? Maybe a good guide for linking and using? Otber than the guide someine else told me to, i wqnt a few guides to learn
Just use the normal mongodb driver - pymongo
!pypi pymongo
Bernie Hackett
Python driver for MongoDB http://www.mongodb.org
Apache License, Version 2.0
either ways; I can't think of any "good guides" as such - they both have excellent documentation
Wjat do you mean by async? The only use for async in my file is:
async def test();
Code block of a command```
well explaining what async is isn't topical for this channel
what are you using this for?
so im trying to create a leaderboard on a bot but it needs I need to get the net worth by adding wallet + bank but by putting that into a sql command raw it prints(['wallet', 'bank']) but I need it to give 1 response and not 2
so you only need the networth back right? why are you doing select * then?
I guess that if i don't know what it is than i am no using it
Wdym by this? This whatM
the query would be something like
SELECT userid, bank + wallet AS networth FROM tablename ORDER BY networth DESC;
cause i need userid from the db too
what is the data you are planning on storing/what application are you using this cluster for
ok
edited
there's a syntax error near AS @burnt turret
huh what database is this?
postgres
just a second
kk
that's odd
i tried it myself and it works
can you show what you've typed in?
@left scaffold
this lb = await self.client.db.fetch("SELECT userid, bank + wallet AS networth FROM economy ORDER BY networth DESC")
and you're sure all those columns exist?
yup
can you show the exact error message?
because I don't see an error with the syntax there;
oh wait nvm it's working now it's just another error now but that isn't related to the db in anyway possible
Hey all, using pymongo:
I want to sort a collection by the number of replies in an array...
questions = list(mongo.db.questions.find().sort("pros", 1))
The problem is, there are two arrays.
"pros" and "cons".
I want to add the number of pros and the number of cons in the array to be the total. So it would be something like:
questions = list(mongo.db.questions.find().sort([size of pros array] + [size of cons array], 1))
But I have no idea how to do that.
hey does anyone have any good stuff to read for sqlite3
i've read the docs
maybe i should watch some videos by corey schafer idk
Why won't it work?
Youre in the python repl
Wdym?
exit() and then try again
Thanks
client = MongoClient(<<MONGODB URL>>)
db=client.admin```
Does this client line replaces this line in my code:
```py
client = commands.Bot(command_prefix='!' , intents=intents)
client = commands.Bot(command_prefix='!' , intents=intents)
No, theyre different clients
so if i have client.get_guild it would be ok?
Just dont name them the same thing
or something else that omst people use the word "bot" for?
To change this?
hello
i use PyMongo
everybody knows that there is a lot of junk in databases
a lot of spam
and some expired 5h1t
i want to write an event
which each 24 hours goes thorugh each document in my collections
checking if it is ok
i already wrote a main sructure
now i need to correctly write if statements with some actions the program takes if document doesnt satisfy it
here are my ifs
If guild/user document has only _id key (delete document)
If guild/user ban (key) timeout expired (value) (delete ban key)
If guild/user premium (key) timeout expired (value) (delete premium key)
i am having problems pls help xD
how do i go through each document in collections in one cluster?
for collection in db.list_collection_names():
for document in collection.find({}):
tried writing smth like that
it doesnt work




