#databases

1 messages · Page 136 of 1

burnt turret
#

username=%s

carmine totem
#

oh and also quary and query

#

yeah

#

thanks problem fixed

#

all thanks to you

burnt turret
#

😄

carmine totem
#

but if you see it i would like to get some help

ripe bronze
fallen bone
carmine totem
#

with what make gui?
@ripe bronze tkinter

neon schooner
#
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

limpid star
#

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

topaz cloak
#

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 ?

barren marsh
#

in sql lite 3 how can i add list data in a TEXT field or is a different field for it?

burnt turret
#

you can just dump the list into the text field in string form, and then while retrieving it, you can use json.loads

barren marsh
#

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?

burnt turret
#

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

barren marsh
#

im a noob ;-; could you elaborate?

burnt turret
#

right now, each element is a discord.Role object

#

it contains a lot of data

barren marsh
#

ok

#

yeahh

burnt turret
#

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

barren marsh
#

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?

burnt turret
#

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

barren marsh
#

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?

burnt turret
#

#bot-commands message an example

barren marsh
#

ohh thanks a lot ill look at the example and give it a try

#

:D

#

@burnt turret it worked!! thank you so very much

burnt turret
#

😄

barren marsh
#

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,))
modest pulsar
#

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,))

prisma girder
novel oak
#

any recommendations to make a DB to register the id's and number of warns of each person of a discord?? thx

tulip cave
#

Hello, is there a way to make global variables? basically variables that can interact with txt files?

prisma girder
tulip cave
#

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

prisma girder
#

So you want to store some variables in server.properties file?

#

Am I correct?

tulip cave
#

yea

prisma girder
tulip cave
#

k ty

prisma girder
#

Your welcome

fallen bone
#

Since days

pure dirge
#

Can integar column in sqlite3 store float numbers

prisma girder
pure dirge
#

Actually I think my problem is
AttributeError: 'str' object has no attribute 'execute'

prisma girder
#

Hard to guess without a code

pure dirge
#

lmao I got it, I named a variable c like an idiot!

indigo smelt
#

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.

warm sage
#

Just pip install psycopg2

#

Then you're done

indigo smelt
#

Already installed that library

indigo smelt
#

Mk

#

So how do I create a database with PostgreSQL

iron summit
#

Anyone know how to read an image from a message and send it to another channel?

#

attachment.save attachment.to_file

#

gg

half kettle
half kettle
#

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?

faint breach
#

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

half kettle
#

Is there a way that I can download/copy all the data of my ‘economy’ table, reset MySQL and then reinstall the downloaded table?

burnt turret
#

I've never used this but it looks similar to pgdump at first glance

mellow rose
#

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.

half kettle
burnt turret
burnt turret
#

Maybe someone else knows

half kettle
#

Oof

modest pulsar
#

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?

burnt turret
#

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?

half kettle
burnt turret
#

Never had to find alternative ways to do this :/ sorry

burnt turret
torn sphinx
#

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.

dawn hill
torn sphinx
dawn hill
#

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?

burnt turret
#

Better icon?

#

What do you mean by that?

indigo smelt
#

How do I create a db in PostgreSQL

quartz geode
#

how do i get alias and quote columns based on serials

ionic marsh
#

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?

burnt turret
indigo smelt
burnt turret
#

CREATE DATABASE dbname creates a database called...dbname

burnt turret
#

Some resources

barren marsh
#

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?

burnt turret
quartz geode
#

Thanks a lot

burnt turret
indigo smelt
#

@burnt turret Doing this CREATE DATABASE money says invalid syntax

burnt turret
#

Every SQL query ends with a ;

quartz geode
burnt turret
indigo smelt
barren marsh
#

also wdym by relational database?

indigo smelt
#

CREATE DATABASE money; Still says invalid syntax

burnt turret
#

Show your query

indigo smelt
#

I dunno how to create a db

burnt turret
burnt turret
burnt turret
indigo smelt
burnt turret
#

...so show the code

barren marsh
#

ohhh that makes sense like table: animals have columns for say dogs cats etc hence relational?

indigo smelt
#

This is all I have lmfao

burnt turret
indigo smelt
#

And importing psycopg2

burnt turret
#

That obviously will be invalid syntax

#

You have to tell psycopg2 to execute the statement

indigo smelt
burnt turret
#

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

indigo smelt
#

I typed exactly what you said to type loll

indigo smelt
burnt turret
#

Well I won't know that without you telling me

#

Open up psql, login to your root account, and run the query I said

indigo smelt
burnt turret
#

After doing that, using psycopg2 to connect to the database will be simpler

indigo smelt
burnt turret
#

You can

#

will be simpler

indigo smelt
#

I'd rather have it not be simpler lol

burnt turret
#

You'll be making the database only once

#

What does it matter if you do it from the code or from the shell

indigo smelt
#

What huh

#

So how do I log in, in the shell then

burnt turret
#

just open it, and it'll prompt you for your login details

#

Type in psql into your computers search bar

indigo smelt
burnt turret
#

Send a screenshot

#

Or you can like just Google how to open psql

indigo smelt
#

ok

#

well i gtg

burnt turret
#

Alright

#

I'd recommend you go over the resources I'd linked earlier

indigo smelt
#

Where r they?

fallen bone
torn sphinx
#

I need help

#

i keep getting this error w/my sqlite3 file (in pycharm)

delicate fieldBOT
#

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:

https://paste.pythondiscord.com

torn sphinx
#

^^ is my error and this is my sqlite3 file:

#

IF anyone can pls check it would mean alot!

fallen bone
#
mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'test'@'localhost' (using password: YES)

How do I get access??

marble osprey
#

can anyone tell me why tkinter crashes when i run this

slim garden
#
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

torn sphinx
#

Is there a dedicated SQL discord server?

slim garden
#

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```
torn sphinx
#

Does anyone have anyclue as to why i get the error?

half gyro
marble osprey
torn sphinx
modest pulsar
#

Hi, is it possible to add a column to an existing table with a default value?

mighty sun
#

Does anyone know about any good tutorials for using databases with python

thorn geode
mighty sun
#

also is this normal for a .db file in pycharm

thorn geode
#

Yes

#

It's not supposed to be opened like that though lol.

mighty sun
#

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

thorn geode
#

You can download a database browser

modest pulsar
runic saffron
#

Hey all, I posted a (pretty simple) question in #help-cake and any help would be amazing.

heavy crater
#

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)

mighty sun
#

with sqlite how do I make it so that everytime I run the python program it doesn't make a new table

runic saffron
#

@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

burnt turret
burnt turret
still urchin
#

It does

#

But only tables. Not columns

burnt turret
#

So, perfect for what they wanted

warm fern
#

What db do you guys usually use with Django?

sterile oracle
#

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

torn sphinx
#

@sterile oracle what you mean good format?

sterile oracle
#

Just an example

torn sphinx
#

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

sterile oracle
#

oh ok thanks

#

i will look into that

bitter ingot
karmic vessel
#

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?

bitter ingot
#

i'm not actually sure

bitter ingot
karmic vessel
#

ty

#

yea not too worried about the py implementation but more just about how i can make queries over 4b records efficient

heavy crater
#

is there a way to directly check a tab from a db? thonk_hmm

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 thonk_hmm

#

this is how the db looks like thonkhappy

hollow abyss
#

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

burnt turret
#

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

prisma girder
burnt turret
#

What's a DI?

hollow abyss
burnt turret
#

!pypi asyncsql

delicate fieldBOT
#
Naw.

Package could not be found.

burnt turret
#

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

prisma girder
#

I have container with DB service and can easily use it in my whole application

hollow abyss
#

!pypi asyncsqlite3

delicate fieldBOT
#
Nah.

Package could not be found.

hollow abyss
#

Tf?

lilac breach
#

hi

burnt turret
hollow abyss
torn sphinx
#

Is better to just assign it to a global var like the bot object which the other person said.

prisma girder
torn sphinx
#

in this case its fine for their bot

#

because the bot is used globally

carmine totem
#

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

wintry peak
#

I'm getting a error here :
Print ("hello")
Error: you are too dumb to learn python

#

Pls help

#

Someone

#

Plz

floral crater
#

Anyone know how tgo import an outlook calender into python

last flax
wintry peak
last flax
#

nppp

rain plank
summer citrus
#

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

burnt turret
#

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

summer citrus
#

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

torpid sky
#

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

rain plank
icy glacier
#

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

royal cosmos
#

Whats wrong with this code? c.execute("""ALTER TABLE botdata DROP COLUMN accountcreated""")

#

It says syntax error near "DROP"

keen spoke
#

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

carmine totem
#

i use python for coding and i imported mysql-connector

carmine totem
#

@rain plank can you help me?

mellow scroll
prisma girder
#

Are your Pi and main computer in same network, right?

mellow scroll
#

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?

prisma girder
#

Pi is your server so open your ports only there

#

Do you have Rasbian?

mellow scroll
#

Raspbian 64bit

mellow scroll
#

ay ty

solemn ridge
#

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))]
torn sphinx
#

hi

prisma girder
#

Instead of --destination-port

mellow scroll
#

that is also unknown

prisma girder
mellow scroll
solemn ridge
#

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

prisma girder
solemn ridge
#

Strings

#

I mean, the type is a string

mellow scroll
prisma girder
prisma girder
mellow scroll
solemn ridge
prisma girder
# solemn ridge Wdym

You have session.add(self) and session.commit() so from where session comes from?

solemn ridge
#

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

prisma girder
#

Hmm, what is type of supreme_id?

#

I am curious about your parameters: [parameters: ((['N/A'], 29528), (['129', '139', '149'], 29624))]

solemn ridge
#

supreme_id is an int

#

['N/A/'] is a serialised list

#

so is ['129', '139', '149']

prisma girder
#

I am not master of sqlalchemy but it looks like you pass tuple of tuples into UPDATE

#

However I may be wrong

solemn ridge
#

Hmm

prisma girder
#

Hard to say for me without ability to debug

solemn ridge
#

I have been trying to fix this for the best 5 hours haha

prisma girder
#

What when you comment sizes field?

#

Or you don't update it

solemn ridge
#

What?

#

oh

#

let me see

prisma girder
#

You can also use pickle column type to store Python objects as blobs

solemn ridge
#

Well I think the problem occurs when creating the object

#

and I can't leave the sizes field blank

prisma girder
#

Have you tried to catch this object with sqlalchemy events?

solemn ridge
#

Oh should I enable echo?

#

echo=True

mellow scroll
#

IM GOING TO SCREAM

#

I have binded the IP to 0.0.0.0

prisma girder
mellow scroll
#

i dont understand why this shit wont work

prisma girder
torpid sky
#

How do I select an entire column and get all the queries in it using sqlite

mellow scroll
#

I can connect via mongo compass now

#

thank you everybody for all the stuff yu helped me with 🙂

solemn ridge
#

@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
delicate fieldBOT
#

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:

https://paste.pythondiscord.com

solemn ridge
prisma girder
solemn ridge
#

Hmm

#

Let me try reprinting the type

prisma girder
#

How about this - dump this field always? No if isinstance(self.sizes, list): because maybe it's iterable?

#

I am guessing now

solemn ridge
#

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'>

prisma girder
#

Are you invoking item_handler several times? I mean - can be here hazard?

solemn ridge
#

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'>
prisma girder
#

When multiple objects is trying to call session.commit()

solemn ridge
#

A lot of times, asynchronously

solemn ridge
prisma girder
#

I recommend to add some Lock

solemn ridge
#

Couldn't find how to fix it

prisma girder
#

I don't know anything about threading-safety for sessions

solemn ridge
#

Hmm

#

I actually didn't think

#

of a lock mechanism

#

Give me a second to adjust my code

prisma girder
#

Right

solemn ridge
#

It did not work..

torn sphinx
#

Does anyone know why this Sqlite3 file wont work in pycharm:

delicate fieldBOT
#

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:

https://paste.pythondiscord.com

torn sphinx
#

^ 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

torn sphinx
#

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

frosty axle
#

how can I get the data from mysql's server, then I mapping into pipeline? is there anyone can teach me?

carmine totem
#

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

burnt turret
#

SELECT fullname FROM users WHERE math_class = 'yes'

carmine totem
#

and how do i save it to list

burnt turret
#

how were you doing it before?

carmine totem
#

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)

burnt turret
#

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)

carmine totem
#

so like instead of execute u use fetchall

#

fetchall saves it into var right?

burnt turret
#

no, after execute you use fetchall

#

and yes fetchall assigns it to the variable

carmine totem
#

command will be:

handler.execute('SELECT fullname FROM users WHERE math_class = "yes"')
list_of_fullnames = handler.fetchall()
#

if i understood?

burnt turret
#

yep

carmine totem
#

than list_of_fullnames will be string i guess right

burnt turret
#

no

#

it'll be a list of lists

#

(or a tuple of tuples)

carmine totem
#

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?

burnt turret
#

wdym by current class though

burnt turret
carmine totem
#

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

burnt turret
#

you need to specify a column that you want to retrieve

#

if you want all columns that's SELECT * ...

#

else

burnt turret
prisma girder
carmine totem
#
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

burnt turret
carmine totem
#

im talking on another problem........

#

i sent the code above

burnt turret
#

you haven't specified a column to retrieve here

#

hence, already answered

carmine totem
#

thank you :):)

#

sorry i was being rude i just didnt understand you

burnt turret
#

all good 😄

carmine totem
#
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

lone adder
#

im getting this error i dont know whats wronghttps://gyazo.com/2feebde08f28adb700bbe0545c4fa409

torn sphinx
#

can anyone say how to get mongodb uri and databse?

spice gust
#

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?

royal cosmos
#

what is wrong with this code, it is giving me an error: c.execute("""UPDATE botdata SET cash =?, inventory =? WHERE userID =?""", (usercash, userinventory, authorname,))

lusty nest
#

try using %s instead of ?

torn sphinx
#

hi

#

can I use a server from another device?

lusty nest
#

I bet you can

torn sphinx
#

well

empty bone
#

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.

lusty nest
#

you should consider going to AVAILABLE HELP CHANNELS

empty bone
#

Thanks

torn sphinx
signal cloak
#

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?

torn sphinx
#

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

brave bridge
#

@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.

torn sphinx
#

oh

#

ok

floral crater
#

How do I link my python code to my MySQL data base?

velvet fable
#

for postgres, how would i get all info from a column from a table?

dense quarry
#

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?

elfin kestrel
#

Hello where do i start with python databases? Videos preferred.

#

(Yes I'm a total noob)

burnt turret
burnt turret
delicate fieldBOT
tardy hamlet
#

!code

delicate fieldBOT
#

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.

tardy hamlet
#
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?

upbeat raven
#

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>'."?

tough grail
#

@upbeat raven maybe show code

#

@tardy hamlet This is a warning, not an error

upbeat raven
#

@tough grail should i dm you?

#

the code?

tough grail
#

If its something you dont want public yeah

#

But you can also just send it here

tough grail
#

delete

#

@upbeat raven delete

#

you need to remove your password from it

upbeat raven
#

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()

tough grail
#

Ok and can you send the full error?

upbeat raven
#

so what im tryna do is read a csv file using pand and then insert into snowflake db

tough grail
#

Also wrap your code in ```

#

```
code here
```

#

Like this

upbeat raven
#

oh ok

tough grail
#

So send the full error message

upbeat raven
#
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'
tough grail
#

Try making it a raw string

#

Oh nvm

#

It already is

upbeat raven
#

get different error when i did

tough grail
#

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')

upbeat raven
#
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"
tough grail
#

Is there something broken in your csv file?

upbeat raven
#

i dont think so lemme try other csv just in case

#

nope same error = invalid identifier '"<new csv file first word/character>"

sterile raft
#
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.

burnt turret
#

There has to be some rows for you to update in the first place

sterile raft
#

Oh true lmao.

torn sphinx
#

hi guys

civic jacinth
#

anyone here familiar with pyrebase ?

torn sphinx
#

why is sqlite3 better than json? anyone knows?

prisma girder
earnest parcel
#

because json is stored in a human readable format and that makes it very inefficient

torn sphinx
#

okay

torn sphinx
true tendon
#

anyone have experience with pandas dataframe?

torn sphinx
#

uhh

#

i see some people say that using json isnt a good choice with discord bots

#

they recommended a database

prisma girder
true tendon
#

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??

torn sphinx
#

@prisma girder yeah but the questions they answered are about like economy system instead of storing configs

torn sphinx
#

If data does not change or very less it’ll be changed then json is ok

smoky flint
#

Im using sqlite and i want to delete a colum choosen by a command in my table

torn sphinx
#

Umm I don’t think is a good idea to allow users to delete columns from a command

#

Do you mean row?

shell wedge
#

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

green parcel
#

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?

burnt turret
#

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

sick obsidian
#

How do I have diffrent guilds have diffrent prefixes?

minor tapir
#

`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')`

keen spoke
#

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

torn sphinx
#

@burnt turret how do I create a file and a table with postgresql?

burnt turret
#

A file?

torn sphinx
#

yes

burnt turret
#

postgres isn't a file based database like sqlite

torn sphinx
#

oh

#

how do I get started then?

burnt turret
#

You install postgresql server

torn sphinx
#

nice pfp btw

burnt turret
#

haha thanks

torn sphinx
#

:notlikeduck:

torn sphinx
burnt turret
#

One sec

#

Descending order by which column?

jovial notch
#

oh someone helped damn

#

ok so

burnt turret
#

Quick, I should be asleep now

jovial notch
#

but it doesnt work

#

like i need

burnt turret
#

If you just need it sorted you should be using ORDER BY

jovial notch
#

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.

keen spoke
#

hey guys

#

what's the difference between mysql and sqllite3

#

i used sqllite3 like once

burnt turret
#

Don't ghost ping

#

So, the same person may be having mutliple rows?

#

@jovial notch

keen spoke
#

i didn't ghost ping

burnt turret
#

Not you, killer

keen spoke
#

oh ok

pure mortar
#

i saw everything

keen spoke
#

so should i use sqllite 3 to create a database for login users or mysql

burnt turret
#

You can use either

#

Sqlite works fine for small projects

pure mortar
#

sqlite3

keen spoke
#

well that's what this app is gonna be so

pure mortar
#

use sqlite3

keen spoke
#

ok great thanks

burnt turret
# jovial notch yes

SELECT steam, count(*) as num FROM tablename GROUP BY steam ORDER BY num DESC
I think?

keen spoke
#

i will be back w questions

pure mortar
#

i should learn sql one of these days

keen spoke
pure mortar
#

ive gotten lucky yet

keen spoke
#

they asked me in the CUNA one

#

i didn't know what to do

pure mortar
#

🕯️

keen spoke
#

yeah they went all out on me in one interview

torn sphinx
#

@burnt turret i installed postgres

#

what next?

keen spoke
#

but seriously sqllite3 is like key for data science

pure mortar
#

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

keen spoke
# pure mortar so intense its like theyre interviewing for a full time

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...

▶ Play video
#

this woman taught herself SQL for the DS interview so

#

i don't wanna get cancelled idk if chick is derogotary now

shell wedge
#

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.

pure mortar
keen spoke
#

crazy shit

pure mortar
#

im a bit more chill so were going the slow track

keen spoke
#

you are more chill than i am

#

i admire that

pure mortar
#

ik my limits

#

if i try too hard ill just burn out

keen spoke
#

oh no i spend a lot of time screwing around

pure mortar
#

esp in DS where theres infinite things to learn

keen spoke
#

like being on this server and talking to people

pure mortar
keen spoke
#

although at the breakneck pace i'm going at it looks like i'm a faangophile

pure mortar
#

youre still young so you still have time

keen spoke
#

pls there are 15 year olds on this server who can code better than us

pure mortar
#

also talking on this server helps you get information passively

#

dude the server owner hasnt even graduated college yet

keen spoke
#

hey i prefer talking to you than my introvert high school friends so

pure mortar
#

and his portfolio is ridic

keen spoke
#

joe?

#

or lemon

pure mortar
#

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

keen spoke
#

yeah i have some friends in UK who are doing that

pure mortar
keen spoke
#

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

keen spoke
#

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?

upper juniper
#

You need to install flask-sqlalchemy to use it

keen spoke
#

yeah so i did pip install flask_sqlalchemy

#

and it installed

#

but it still won't work

upper juniper
#

Errors?

keen spoke
#

is it a problem with the linter??

upper juniper
#

Show your import statement

jaunty galleon
#

Hello

#

i want to start using MongoDB, any recommended website for it?

upper juniper
#

Their docs

jaunty galleon
#

Can you send it?

upper juniper
#

I dont have a link handy

jaunty galleon
#

Ok

#

I'll look up in the interner

#

Thanks

#

That?

upper juniper
#

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

jaunty galleon
upper juniper
#

Python package for connecting to mongodbs

keen spoke
#

basically just doxxed myself but that's ok

upper juniper
#

Whats that

keen spoke
#

oh my bad

upper juniper
#

Thats just the terminal

keen spoke
#

it's from this tutorial if that helps

upper juniper
#

Ok all of that looks decent

#

Try running it

#

Wait

keen spoke
#

ModuleNotFoundError: No module named 'flask_sqlalchemy'

upper juniper
#

Vscode right?

keen spoke
#

yes

upper juniper
#

Open the terminal in it and then the python interpreter

keen spoke
#

huh?

#

open the terminal in VSC?

upper juniper
#

The integrated terminal

keen spoke
#

that's the integrated terminal right

upper juniper
#

Ye

#

Okay now do python3 -c "from flask_sqlalchemy import SQLAlchemy"

keen spoke
#

bash: python3: command not found

upper juniper
#

Whats the command for python then

#

Replace that into python3

#

py3 maybe?

#

py

#

Idk

jaunty galleon
#

Wait, i made an account and started a cluster

keen spoke
#

idk either

jaunty galleon
#

How can i cinnect the python file to the database

upper juniper
#

You dont know what your python command is?

#

How are you running your apps then

keen spoke
#

FLASK_APP=app, FLASK_ENV=development, flask run

jaunty galleon
keen spoke
#

it might be py

#

also should i be using quotes like this "from flask_sqlalchemy import SQLAlchemy" @upper juniper

upper juniper
#

Yes

#

This is just making sure you have it installed and python can import it

keen spoke
#

nope py doesn't work either

upper juniper
#

Ok anyway just do pip show flask_sqlalchemy

keen spoke
#

nothing happened

upper juniper
#

Then you dont have it installed

keen spoke
#

but i did install it

upper juniper
#

Do you have a venv

keen spoke
#

no

upper juniper
#

Go to your terminal and do pip freeze | grep "flask"

keen spoke
#

ok i did pip install flask_sqlalchemy in the integrated terminal

upper juniper
#

And check there

keen spoke
#

and one of the red squigglies went away

upper juniper
#

Ok

#

Try running the app again

keen spoke
#
 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)

upper juniper
#

I would personally use from project.filename import function instead of that

keen spoke
#

ok let's try that

upper juniper
#

Whats your project called

keen spoke
#

Web App Drawing 2

#

from Web App Drawing 2._init_py import auth as auth blue_print?

#

no that doesn't work

upper juniper
#

Is your root directory really called "Web App Drawing 2"

#

Why lmao

keen spoke
#

what is it supposed to be called

#

i thought it could be called anything

upper juniper
#

Idk, something shorter and without spaces?

keen spoke
#

ok i'll do that next time

#

sorry

upper juniper
#

Alright whatever, from .auth import the_blueprint

keen spoke
#

nope still a squiggly under from

upper juniper
#

But does it work

keen spoke
upper juniper
jaunty galleon
#

All of them are about atlas something

upper juniper
#

Bruh, replace the variable to whatever the blueprint is called

#

Atlas is cloud mongodb

#

And you can also setup a local instance

keen spoke
#
 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

upper juniper
#

Is the thing youre importing called the_blueprint?

#

I was just giving an example

keen spoke
#

yeah i took it from the tutorial

upper juniper
#

Show me

keen spoke
#
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

upper juniper
#

Show me the auth file

jaunty galleon
upper juniper
#

Theres an example right there on the first page

keen spoke
#
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

jaunty galleon
#

Wait MongoDB is json?

upper juniper
#

Its json-like

jaunty galleon
#

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

upper juniper
#

Those arent python commands

#

Just setup the db and then read the pymongo docs

#

To interact with it using python

jaunty galleon
#

Buy i don't know how to set the db

#

i opened a cluster

jaunty galleon
#

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```
keen spoke
#

idk mongo db so i can't help lmao

jaunty galleon
#

Yeah no prob

pure mortar
#

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

jaunty galleon
#

I need someone that knows

thick grove
#

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?

modest pulsar
#

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))
brazen charm
#

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

modest pulsar
#

wait i try something

brazen charm
#

well, you're selecting every row from the table user_id

modest pulsar
#

so how can i fetch all values of a column?

#

@brazen charm pls sweat

keen spoke
#

Perhaps

modest pulsar
valid vault
#

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

torn sphinx
#

how do I create and setup a table with sqyncpg?

keen spoke
#
    with sqlite3.connect("db.") as db:
#

guys what does that line do

#

pls explain

tacit umbra
#

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

tacit umbra
keen spoke
#

@tacit umbra idk what that means

tacit umbra
#

Why not?

keen spoke
#

Bc I’ve only used sql like twice

#

am noob

pure mortar
#

why is installing mysql such a process

#

keeps giving me errors

#

gonna try to downgrade

jaunty galleon
#

So how do i connect between mongoDB cluster and discord.py file?

novel oak
#

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)
prisma girder
# jaunty galleon Anyone?
MongoDB

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.

jaunty galleon
novel oak
#

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)
prisma girder
jaunty galleon
#

MongoDB Atlas

prisma girder
primal cave
#

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

jaunty galleon
#

I went on the website and opened a cluster

jaunty galleon
jaunty galleon
#

Anyone?

prisma girder
jaunty galleon
prisma girder
jaunty galleon
#

I look into it in a few minutes

#

I just want to know if it is what i need

burnt turret
#

why do you say "i dont want this atlas" though?

#

it is mongodb's cloud hosted database as a service option

jaunty galleon
#

Because I was told i don't need to download this and it is better not to

burnt turret
#

you don't have to download atlas

#

it's cloud-hosted

jaunty galleon
#

So what is the difference?

burnt turret
#

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

jaunty galleon
#

So the atlas is for multiple servers?

burnt turret
#

I don't understand what you mean by that

jaunty galleon
#

Why is it better to use the atlas than the normal cluster?

burnt turret
#

what do you mean by "normal cluster"? you are using a cluster on atlas

left scaffold
#

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
burnt turret
#

you can do that in your query like;

SELECT bank, wallet, bank + wallet AS networth FROM tablename;
left scaffold
#

ah okay thanks

jaunty galleon
burnt turret
#

the website you're using is atlas

#

the service that is providing you the cluster online is what is called mongodb atlas

jaunty galleon
#

Oh

#

So

#

I am already using atlas?

burnt turret
#

yes

#

I don't know of any other cloud-hosted cluster solution for mongodb at least

#

so most likely yes

jaunty galleon
#

I opened a cluster for free with 512 mb storage

#

Ia that it?

burnt turret
#

yes

jaunty galleon
#

Oh perfect

left scaffold
#

@burnt turret so would this be correct? SELECT * FROM economy ORDER BY bank + wallet AS networth DESC

burnt turret
#

No

#

what are you trying to do exactly?

jaunty galleon
#

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

burnt turret
#

!pypi pymongo

delicate fieldBOT
burnt turret
#

If you're using this for something async,

#

!pypi motor

delicate fieldBOT
burnt turret
#

either ways; I can't think of any "good guides" as such - they both have excellent documentation

jaunty galleon
burnt turret
#

well explaining what async is isn't topical for this channel

#

what are you using this for?

left scaffold
# burnt turret what are you trying to do exactly?

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

burnt turret
#

so you only need the networth back right? why are you doing select * then?

jaunty galleon
jaunty galleon
burnt turret
#

the query would be something like

SELECT userid, bank + wallet AS networth FROM tablename ORDER BY networth DESC;
left scaffold
burnt turret
left scaffold
#

ok

burnt turret
left scaffold
#

there's a syntax error near AS @burnt turret

burnt turret
#

huh what database is this?

left scaffold
#

postgres

burnt turret
#

just a second

left scaffold
#

kk

burnt turret
#

that's odd

#

i tried it myself and it works

#

can you show what you've typed in?

#

@left scaffold

left scaffold
#

this lb = await self.client.db.fetch("SELECT userid, bank + wallet AS networth FROM economy ORDER BY networth DESC")

burnt turret
#

and you're sure all those columns exist?

left scaffold
#

yup

burnt turret
#

can you show the exact error message?

#

because I don't see an error with the syntax there;

left scaffold
#

oh wait nvm it's working now it's just another error now but that isn't related to the db in anyway possible

shell wedge
#

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.

keen spoke
#

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

jaunty galleon
#

Why won't it work?

upper juniper
#

Youre in the python repl

jaunty galleon
#

Wdym?

upper juniper
#

exit() and then try again

jaunty galleon
#

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)
upper juniper
#

No, theyre different clients

jaunty galleon
#

so if i have client.get_guild it would be ok?

upper juniper
#

Just dont name them the same thing

jaunty galleon
#

or something else that omst people use the word "bot" for?

haughty ravine
#

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