#databases

1 messages · Page 129 of 1

burnt turret
#

initially i'd tried something like

WHERE date_part('day', date_col) = date_part('day', current_date)
proven arrow
#

There's no difference. Execute just makes it compliant with SQL standard

#

Both do the same thing.

burnt turret
#

Right, that makes sense. Thanks.

burnt turret
#

If i initially made a table with a column set as SERIAL, is it possible to make it GENERATED ALWAYS AS IDENTITY with an alter statement?

#

I just read that the second option will prevent accidentally inserting values into that column

torn sphinx
#

Code:

with open('book.json') as jsondata:
  data = json.load(jsondata)

while True:
    query = input("Enter query: ")
    


    print(f"{Style.RESET_ALL}{Fore.GREEN}Name: {list(filter(lambda x:x['name']==query,data))}\n"
          f"Monthly searches: {list(filter(lambda x:x['val']==query,data))}")

Printed out:

Name: [{'name': 'Peru', 'val': '27.100'}]
Monthly searches: []

I am trying to make a search kinda thing and i only want the item name and the item val single

proven arrow
#

But you would have to drop the current sequence first before altering

burnt turret
burnt turret
proven arrow
#
DROP SEQUENCE schema.sequence_name;

ALTER TABLE schema.t1 ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY (RESTART some_value);
#

your schema is probably public so just replace where I have schema with that

#

And some_value is what you want to resume from.

burnt turret
#

what does the RESTART do?

#

oh right

proven arrow
#

Also you might have to drop defaults first

burnt turret
#

right, thanks!

#

are these SERIALs and GENERATED ... actual datatypes like varchar/char?

proven arrow
#

ALTER TABLE schema.tablename COLUMN id DROP DEFAULT

#

Yes

#

But will be int or bigint

burnt turret
#

oh, makes sense

#

in the alter column, don't we use ADD for constraints though? but while creating a table, we pass in SERIAL in the place where we'd pass in a data type; which confused me

proven arrow
#

I'm not sure what you mean?

burnt turret
#

actually, i might've misunderstood ALTER

#

oh, and is there some way to convert text to lowercase or something before matching?

#

in case i have data that have uppercase characters, how would i query it if the input was all lowercase

proven arrow
#

You can use the lower () function

burnt turret
#

oh, thank you!

#

postgres really has everything covered huh 😄

proven arrow
#

Yeah it's pretty good, although I don't use it as much

burnt turret
#

oh, why's that?

#

i'm taught mysql at school, but i chose postgres because everyone seems to recommend it for discord bots

proven arrow
#

Well that graph is only for the driver/module

#

And MySQL is also perfectly fine. A lot of people seem to hate it for what it was like in the past. And then sometimes it's the circles your in where if one says X is good then everyone just repeats that.

#

But I'm sure postgres isn't perfect either. Oracle would be the real beast in this comparison game 😅

burnt turret
#

why is mysql hated though? what was it like before?

slender rose
#
await db.execute("""UPDATE votes SET (count = count+1, timer = $2) WHERE id = $1""", user.id, str(datetime.utcnow()))```
#

any idea why it's giving me a asyncpg syntax error near =

burnt turret
slender rose
#

yes thats true

#

mysql is pretty bad

#

mysql is slow as fuck

burnt turret
proven arrow
proven arrow
proven arrow
#

MySQL is rarely the problem for most people. It's shitty architecture and design that causes problems.

slender rose
#

i used mysql for a long time and it was pretty stupid for me so i'd agree with dpy

#

anyway any idea for a solution to my problem?

proven arrow
#

Well most of the points in that image don't really mean much if you understand what's going on. For ex, many people using database don't even know what DDL is and if they did they would know it's not that big of an issue.

slender rose
#

lol

#

if i wanted to increment a value in sql would be like SET count = count + 1, time = $1 WHERE id = $2?

proven arrow
#

Yeah

slender rose
#

im not sure if it was because of putting () around count = count + 1, time = $1 last time it gave me an error

#
asyncpg.exceptions.PostgresSyntaxError: syntax error at or near "="```
#

this

proven arrow
#

Don't put it in brackets

slender rose
#

oh

#

also do we put commas between each values that we're about to update?

proven arrow
#

Yeah

slender rose
#

like count = ... , time = ...

#

oh thanks

autumn epoch
#

How do save all of the data from a SQLite database to a variable, then filter out to a certain match

weak tinsel
#

i guess MySQL from versions 5.5 and below or something had some problems?

autumn epoch
weak tinsel
#

im waiting for Lufthansa to answer 😄

autumn epoch
#

lol

#

Hes offline ):

#

Nvm figured it my self

#

Actually I need help again.

#

So I was able to get all of the information, but I want to update 1 of the int's by 1. Is that possible and if so how do I do it?

teal wasp
#

hi guys, i need some help with mongo db

#
pymongo.errors.ServerSelectionTimeoutError: No primary available for writes, Timeout: 30s, Topology Description: <TopologyDescription id: 6006f8ec04a73a5bd7ead835, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('cluster-shard-00-00.l3jul.mongodb.net', 27017) server_type: RSSecondary, rtt: 0.07734612872947946>, <ServerDescription ('cluster-shard-00-01.l3jul.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('connection closed')>, <ServerDescription ('cluster-shard-00-02.l3jul.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('connection closed')>]
#

this is a error i am getting

#

(i am using this with discord.py but the error seems to be about mongo)

proven arrow
weak tinsel
#

oh ok , thanks :)

weak tinsel
#

so

autumn epoch
#

Ok

weak tinsel
#

oh nvm, its not py related

autumn epoch
#

Because it just says UPDATE

#

And that is invalid syntax

proven arrow
autumn epoch
weak tinsel
#

cursor.execute("select moneymade from table where condition")

#

or fetch idk

proven arrow
#

It's better if you can provide your table structure and more detail of what you are trying to do. But generally if you want to update a columns value then you can do:
UPDATE table_name SET column_name = column_name + 1 WHERE some_condition

#

That would add 1 to the current value

autumn epoch
#

Well I am making a xp system and I have 'id, xp, level'

#

And I am trying to make the xp go up 1

#

Also the table is called users

weak tinsel
#

mysql?

#

@autumn epoch

autumn epoch
#

?

weak tinsel
#

which one

jolly pond
#

wht do u guys think?

#

intro = input("""welcome to the government
seacret database please fill in your information.
if you wish to continue type next""")

if intro == "next":
ID = int(input("enter your ID"))

while intro != "next":
intro = input("""welcome to the government
seacret database please fill in your information.
if you wish to continue type next
NOTE:YOU ONLY HAVE 1 MORE TRY REMAINING """)
if intro == "next":
ID = int(input("enter your ID"))

x = input("to access please enter your password")

if x == "happyday":
print("access granted welcome comrade",ID)

elif x != "happyday":
print("access denied")
y = input("try again?1")

if y == "yes":
x = input("please enter your password")

elif y == "no":
print("throwing you out the system")

else:
print("enter either yes or no")
y = input("tryagain?")

if x == "happyday":
print("access granted")

while y == "no":
print("instaling hacking software onto your computer")

while x != "happyday":
x = input("please enter your password")

weak tinsel
#

postgre? mysql?

autumn epoch
#

sqlite3

weak tinsel
#

oh

#

the syntax should be the same

autumn epoch
#

YEs

torn sphinx
#

how do i use the motor module with mongo db ?

burnt turret
#

tutorial on their docs, comes with examples

pure dirge
#

hi i need advice on what i should to build my database in

#

it's all in csv's right now

little anchor
#

Hey! I currently have an application on user's pcs that connects directly to my database. I want to know how can I prevent someone from just cracking my code and going into my database. What can I do? The client that they download only needs to insert. Is there a way I can make it so it can only insert to a certain collection and thats it? Or what can I do

torn sphinx
#

Are Excel questions welcome in here? 😬 I know it's not a database..

karmic palm
#

can anyone help me connnect postgresql to flask?

ancient fog
#

newbie question: i just started today with sqlite3. i want to add a entry (idk how to call it tho.. i guess you can call it rows???). i want it to look something like this:

before:

last_name: Jass

after:

last_name: Jass
age: 27

I just started today so... yeah...................................................

smoky pendant
#

with sqlite3 u usually have tables

#

kinda like an excel table in a sense

#

from ur example it seems that ur table needs an extra column to hold the age

ancient fog
#

yes

#

how do i do that?

#

if its possible

smoky pendant
#

u familar with sql syntax

ancient fog
#

a bit

smoky pendant
#

i think sqlite3 might have like a editor thingy

#

where u can directly change ur tables without needing sql syntax

#
ALTER TABLE table_name
ADD COLUMN column_definition;
``` well this is from google
ancient fog
#

oh

#

so cursor.execute("ADD COLUMN ('age')") right?

#

or at least something like that?

smoky pendant
#

uh u need to specifiy the table @ancient fog

#

like u need the ALTER TABLE and say what table u want to change

ancient fog
#

oops. ill appreciate if you show me how to do it

smoky pendant
#

like im not familar with sqlite syntax but from google ur string has to be 'ALTER TABLE <ur_table_name> ADD COLUMN age;'

#

u didnt tell me what table those columns were from

#

so u have to fill that info in urself in where it says ur_table_name

ancient fog
#

is this ok?
cursor.execute(" ALTER TABLE crep ADD COLUMN 'age' ")

#

i forgot to put a datatype in the 'age' so imagine its 'age text'

smoky pendant
#

i tihnk u dont need to encase ur column name in a string @ancient fog

#

unless thats a sqlite thing?

ancient fog
#

no thats a python thing i think

smoky pendant
#

like 'age'

#

i think its just age without the ''

ancient fog
#

ok then

torn sphinx
#

Btw if you are using placeholders don't do that for tables and columns

#

They won't work

bronze nebula
#
    vals = ", ".join(row)
    keys = ", ".join(row.keys())
    stmt = f"insert into `characters` ({keys}) values ({vals});"
    conn.cursor().execute(stmt, list(row.values()))
    print(stmt)
    conn.commit()
    conn.close()```
#

Ah never mind, used row not row.values() in line 1

#

Now I have to figure out how to sanitize this data 😄

slender rose
#

Should we close our connections to postgres or keep it alive after work is done

slender rose
#

INSERT INTO

#

not insert into

bronze nebula
#

That's just convention

bronze nebula
slender rose
#

ah okay

#

im not sure why but my database isn't updating

#

await db.execute("""UPDATE votes SET voted = $1 WHERE id = $1""", "no", member.id)

#

idk why its not updating

#

oh okay wait

#

fuck

wet sierra
#
File "TESTER_BOT.py", line 42, in get_pre
    c = await db.execute("SELECT prefix FROM guilds WHERE guild_id = (?)", (message.guild,))
  File "C:\Python\lib\site-packages\aiosqlite\core.py", line 175, in execute
    cursor = await self._execute(self._conn.execute, sql, parameters)
  File "C:\Python\lib\site-packages\aiosqlite\core.py", line 122, in _execute
    return await future
  File "C:\Python\lib\site-packages\aiosqlite\core.py", line 98, in run
    result = function()
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.
#

help

burnt turret
wet sierra
#

oh yeah

#

nvm

#

thanks

solemn root
#

I know I need a database for my discord bot, but idk how I’d make it so that my bot updates the database anytime a user interacts with the bot. I have the standard format:


CREATE TABLE info (id INTEGER PRIMARY KEY,
user_cash INTEGER,
user_token INTEGER);

INSERT INTO info (1, 3, 5);
INSERT INTO info (2, 6, 3);
INSERT INTO info (3, 10, 9);
INSERT INTO info (4, 2, 4);
INSERT INTO info (5, 7, 6);

SELECT * FROM info;```

How do I modify the query (once the table is made) to constantly update upon user interaction, and allow myself to view the “current” data at any point in a clean, readable manner?

Discord API in Python I get:
```[(1, 3, 5), (2, 6, 3), (3, 10, 9), (4, 2, 4), (5, 7, 6)]```
In an sql file, this:
```1|3|5
2|6|3
3|10|9
4|2|4
5|7|6```

...I’m confused

Neither display column names, which has me puzzled. How come the columns don’t show as  a header for the table?
proven arrow
#

@solemn root To update values you can use the update statement. For example, UPDATE info SET user_cash = 100 WHERE user_token = 5.

#

And it doesn't show column names by default and instead just returns a collection of tuples.

frozen quail
#

Hello is there any easy way in .fetchall() to change datetime.datime() object column to .isoformat()

#

other than enumerating and calling .iso format on every row

#

?

torn sphinx
#

how can we use WHERE with two properties like

"SELECT names FROM shop WHERE items,currency = ?,?"```
#

in sqlite

burnt turret
#

you should be using AND/OR there depending on what you're trying to do

SELECT names FROM shop WHERE items = ? AND currency = ?
#

this will return names from shop where both conditions are met

#

if you use OR, it'll return names where either of the conditions are met

torn sphinx
#

hey

#
hub = input("Enter \"HELP\" to view commands: ")
help = input("Commands: \n------------------------------\n\"LIST\": Views helplist of buyers and plans.\n------------------------------\n\"ADD\": Shows menu to add a user to the list.\n------------------------------\n\"REMOVE\": Shows menu to remove a user from the list.\n------------------------------\n\nInput: ")

db = ["User : Plan Expiry"]


if help == "ADD":
    user = input("Enter buyer's username: ")
    plan = input("Enter buyer's plan expiry: ")
    print("Added " + user + " with " + plan + " expiry to the list.")
    db.append(user + ":" + plan)
if help == "add":
    user = input("Enter buyer's username: ")
    plan = input("Enter buyer's plan expiry: ")
    print("Added " + user + " with " + plan + " expiry to the list.")
    db.append(user + ":" + plan)
if help == "Add":
    user = input("Enter buyer's username: ")
    plan = input("Enter buyer's plan expiry: ")
    print("Added " + user +" with " + plan + " expiry to the list.")
    db.append(user + " : " + plan)

if help == "LIST":
    print(db)
elif help == "List":
    print(db)
elif help == "list":
    print(db)

if hub == "HELP":
    print(help)
elif hub == "help":
    print(help)
elif hub == "Help":
    print(help)
else:
    print("Invalid Syntax")
#

im making a tool

#

to manage some of my companys customers plans

#

for some reason the ADD and REMOVE isnt working

#

help pls <3

torpid sky
#

#conn = sqlite3.connect("mute.db")
#c = conn.cursor()
#c.execute("CREATE TABLE mute(guild_id INT, #userid INT)")
It says there no such table as mute
but the table is right there

#

help

brazen charm
#

do you actually commit said change

torpid sky
#

await conn.execute(sql, val)
await conn.commit()

#

yes

#

but the error is on the line above it

minor venture
#

PLEASE PING ME

slender rose
#

I think you do smth like Py INSERT INTO .... ON DUPLICATE KEY UPDATE .....

minor venture
#

ok thanks!

sonic whale
#

I want to change the timezone setting in clearDB. But there's an error saying that we don't have enough permission. What should I do??

#

I want```
SET GLOBAL time_zone='Asia/Seoul';

But```
Error Code: 1227. Access denied; you need (at least one of) the SUPER privilege(s) for this operation```
#

plz help 😭 😭 😭 😭

golden warren
#

What mean: Error binding parameter 1 - probably unsupported type.

#

In sqlite3

#

@sonic whale Linux?

golden warren
#

At creation or when i insert values @burnt turret ?

sonic whale
golden warren
#

Elevate your powershell @sonic whale

burnt turret
golden warren
# burnt turret the query which raises this error
self.db.usersdb_cursor.execute(
            'INSERT INTO infractions(user_id, user_name, moderator_id, moderator_name, reason, infraction_number) VALUES(?, ?, ?, ?, ?, ?)', (user.id, user, moderator.id, moderator, reason, infraction))

burnt turret
#

which the database doesn't support

golden warren
#

Damn.

burnt turret
#

By the name of the column I assume you want to insert user.name

#

and also moderator.name

golden warren
#

I try okay.

#

I go eat.

burnt turret
#

There isn't much point storing that data though, just storing the IDs should be enough

golden warren
#

@burnt turret sqlite3.InterfaceError: Error binding parameter 3 - probably unsupported type.

burnt turret
#

and when you need their names there are discordpy functions to get the Member object back using the ID

golden warren
#

Whut?

burnt turret
golden warren
burnt turret
#

huh. can you show the code where you define user and moderator?

golden warren
# burnt turret huh. can you show the code where you define `user` and `moderator`?
@commands.command(name='warn', enabled=True)
    async def warn(self, ctx, user: discord.Member, *, reason=None):
        moderator = ctx.author

        self.db.usersdb_cursor.execute(
            'SELECT infraction_number FROM infractions WHERE user_id == {0}'.format(user.id))
        await ctx.send(self.db.usersdb_cursor.fetchall())

        infraction = 0

        if reason is None:
            reason = 'No reason provided.'
        else:
            pass

        self.db.usersdb_cursor.execute(
            'INSERT INTO infractions(user_id, user_name, moderator_id, moderator_name, reason, infraction_number) VALUES(?, ?, ?, ?, ?, ?)', (user.id, user.name, moderator.id, moderator.name, reason, infraction))
        self.db.usersdb.commit()
        await ctx.send(f'{moderator} + {moderator.id} + {user} + {user.id} + {reason}')

burnt turret
#

that's odd; i don't see why that shouldn't work

#

There isn't much point storing that data though, just storing the IDs should be enough
and when you need their names there are discordpy functions to get the Member object back using the ID
this is better IMO

#

avoid storing unnecessary data

#

after all, the user and moderators names could change later on, making your data inaccurate

#

also unrelated to the question but:

  1. don't use f-strings/str.format() in queries - #databases message
  2. for a discord bot you should be using aiosqlite, as sqlite is blocking
golden warren
#

Okay i'm going to try.

#

After i go eating, thx for help :)

sonic whale
#
mysql> SET GLOBAL event_scheduler = ON;
ERROR 1227 (42000): Access denied; you need (at least one of) the SUPER privilege(s) for this operation

In clearDB. What should I do?

#

I use heroku and use add-on clearDB.

sonic whale
#

ClearDB doesn't give Access Permission. Oh, damn it

golden warren
burnt turret
#

Your discord bot is asynchronous, while sqlite is synchronous

#

so everytime you try doing something with the database, it'll block execution

#

and your bot won't respond for that time

#

using aiosqlite module will make your database interaction asynchronous as well

#

so that your bot won't freeze

burnt turret
golden warren
#

Okaaaaay, i finished with sqlite and i try with aiosqlite.

#

Thx :)

golden warren
burnt turret
#
UPDATE infractions SET infraction_number = infraction_number + 1 WHERE user_id = <>
```something like this
golden warren
#

Oh i see! Yes thx ;)

young seal
#

Anyone have experience using ssis and python? Pls ping, just looking for beginner tips to jumpstart myself with

fervent bramble
#

can someone join me in help-aluminum. I have an issue with Django communicating to a postgresql database, i dont know why

crystal olive
#

'Hello to all : I need help to figure a correct syntax issue with mysql.connector...
I would like to add a list of dictionaries into a table. All the dictionaries have the same keys but different values.
The names of the columns of the table have the same name like the keys.

dicolist = [{'code': 'val1', 'name' : 'val2', 'description': 'val3'}, {'code': 'val10', 'name' : 'val20', 'description': 'val30'}, {'code': 'val11', 'name' : 'val12', 'description': 'val13'}]

query = "INSERT INTO product (code, name, description) VALUES ('%s','%s','%s')" % ?????

self.cursor.execute(query)
self.connect.commit()```

I don't know how to write the values of the query... 
Can somebody help me ?
lost pendant
#

Any good resources that anyone is aware of for database implementation with discord.py?

solar pollen
#

If you just want to implement, say, asyncpg with discord.py, here's an example:

#
async def run():
    credentials = {"user": "username", "password": "", "database": "database_name", "host": "127.0.0.1", "port": "5432"}

    async with asyncpg.create_pool(**credentials) as database:
        bot = YourBot(command_prefix="!", database=database)

        for extension in EXTENSIONS:
            bot.load_extension(extension)

        await bot.start("token")


loop = asyncio.get_event_loop()
loop.run_until_complete(run())
#

And then, in your bot class, you can:

lost pendant
#

I have little database experience, I do have a pretty cool bot that I’ve developed. I’d like to be able to use it across multiple servers with server specific settings. So I’m looking for something to reference that will maybe point me in the right direction on how a database is generally used with discord.py

solar pollen
#
class YourBot(commands.Bot):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.database = kwargs["database"]

    @commands.command()
    async def example(self, ctx):
        await self.database.fetchrow("query")
#

These are some modified examples from my bot

#

Using asyncpg

#

@lost pendant

lost pendant
#

Thanks so much my friend

#

@solar pollen

solar pollen
#

No problem :D

fiery bone
#

I can't connect to my database for some reason

smoky pendant
#

does the user ur using have the right password and permissions @fiery bone

fiery bone
#

@smoky pendant Yes, I've tried even creating a new user with all privilages

#

It still says

(10061 No connection could be made because the target machine actively refused it)
#

I've allowed the port through windows firewall

#

When I disables windows firewall I got a new error message

#
(10060 A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond)
torn sphinx
#

@fiery bone - if the connection is being actively refused the server may not allow remote connections - check your pg_hba config file

#

that is a postgres answer - darn - but sounds like remote connections are not allowed on the server itself

fiery bone
#

well it is a vps

#

when I installed mysql I did set it to allow remote connections I'm pretty sure

torn sphinx
#

if you run netstat do you see the port opened for localhost or 0.0.0.0 - localhost(127.0.0.1) only allows local connections while 0.0.0.0 will allow external connections

fiery bone
#

it's localhost

torn sphinx
#

check your config file and make any chances necessary to allow remote access

fiery bone
#

yay new error!!

#

now it says my specific host is not allowed to connect

#

I just have to whitelist it

radiant elbow
#

Any reason not to think that means exactly what it says? It expected a date or a datetime, and instead you passed a timedelta.

fiery bone
#

WOOHOO!! @torn sphinx you are a legend!!

torn sphinx
#

glad I could help

radiant elbow
#

And which of those lines does the traceback say the error is on?

#

The traceback is telling you what's wrong.

#

It's telling you which line is wrong, and what's wrong on it.

jovial notch
radiant elbow
#

Which line is the problem on?

#

ok - so you're trying to pass t2 into the database as a parameter, and t2 is a Timedelta, and the database doesn't want a Timedelta, it wants a date or a datetime

jovial notch
#

Should I do it BIGINT or INTEGER?

foggy iron
radiant elbow
#

you can't add two timestamps together

#

"what's now plus tomorrow" is nonsense

#

if it's supposed to store a duration, or the difference between two times, then you're looking for an INTERVAL column.

#

if it's supposed to store a timestamp, then TIMESTAMP WITHOUT TIME ZONE is the right type to use, but you need to pass a date or a datetime

foggy iron
#

its for me? . _.

jovial notch
radiant elbow
foggy iron
#

oh ok

radiant elbow
jovial notch
#

like if u see my code u will understand

#

i have a system like

radiant elbow
#

I have seen your code, and don't understand.

jovial notch
#

when u do !on it stores the time

#

and when u do !off

#

it tells u how much timed passed

#

not i want a total !time for how many times the person has done the commands

radiant elbow
#

so how much total time has elapsed between !on and !off commands? If they do a !on at time 0 and a !off at time 3 and a !on at time 12 and a !off at time 15, you want 6?

jovial notch
#

u right

#

thats why i got 2 tables

#

but somehow it doesnt work

radiant elbow
#

then TIMESTAMP WITHOUT TIME ZONE is entirely the wrong type, and you want an INTERVAL column instead.

#

that represents a duration.

#

TIMESTAMP represents a day and time. INTERVAL represents a number of seconds.

jovial notch
#

yes but i dont have a type lf seconds do i?

#

i got like month/day/year minutes/seconds/milliseconds

radiant elbow
#

no, you don't.

#

you had that, but then you subtracted it from another month/day/year minutes/seconds/milliseconds, and the difference between two of those is a number of seconds.

#

That's what this is doing: ```py
t2 = timedelta.Timedelta(ctx.message.created_at - tm['time'])

jovial notch
#

oh u right so what should i store in my bottom queries then?

radiant elbow
#

the total amount of time that something has been on is a duration, which means you want an INTERVAL column.

jovial notch
#

so t2.total_seconds() to get hours and minutes?

radiant elbow
#

INTERVAL columns want a datetime.timedelta as their value.

#

there's no need to pull hours and minutes out of it.

radiant elbow
#

so you're trying to subscript None on this line: ```py
t2 = timedelta.Timedelta(ctx.message.created_at - tm['time'])

#

subscripting is using []

#

which tells me that tm is None

jovial notch
#

Doesnt seem to work @radiant elbow should i just store the seconds?

#

t2.total_seconds() as INTERVAL/

radiant elbow
#

where did tm come from? Wherever you got tm from, it gave you a None.

#

it probably came from a column whose value was null

jovial notch
#

it is not none though @radiant elbow

radiant elbow
#

yes, it is. print it.

#

Python's error messages aren't lying to you.

#

that looks reasonable.

jovial notch
#

no errors at all

radiant elbow
#

is this unrelated to the last error you showed?

jovial notch
#

nope

#

last error is just some "python or postgres" unkown error

#

but code works

#

it just throws an error

#

no reason 😛

radiant elbow
#

the last exception you showed was at:

  File "C:/Users/NtinosThanos/PycharmProjects/Greek Mafia Roleplay Bot/Paradox Roleplay.py", line 138, in off
    t2 = timedelta.Timedelta(ctx.message.created_at - tm['time'])
TypeError: 'NoneType' object is not subscriptable
#

I don't see that line in the latest thing you pasted.

jovial notch
#

yes that error

#

is fixed

#

i mean i still get the error but its working

#

its from another code

#

now the code up there doesnt work and i think its some problem with how i get things from db

radiant elbow
#

"doesn't work" how?

jovial notch
#

like is the query right?

radiant elbow
# jovial notch like is the query right?

no, the query is not right. You're using group by, which means that all of the columns that you select must either be included in the group by clause or be the result of aggregate functions. member_id is not.

#

I don't know what timedelta.Timedelta is - why aren't you using datetime.timedelta?

jovial notch
#

@radiant elbow wait so what i need to change in the query

#

so i get like the time and member_id from someone but it goes from most time to lowest

radiant elbow
#

what is the query supposed to be doing?

jovial notch
#

if u get me

radiant elbow
#

then you don't want a group by at all.

#
SELECT time, member_id AS NUM FROM paradoxtotalactivity ORDER BY TIME DESC
jovial notch
#

i dont need AS NUM too right? @radiant elbow

radiant elbow
#

probably not.

#

that would make it so you access the column using "num" instead of "member_id" in your Python code.

craggy jewel
#

Does anyone know how to delete a table from sqlite

#

c = cursor

#

i want to delete memes coloum

#

pls help me

burnt turret
#

Do you want to drop the table or the column?

craggy jewel
radiant elbow
craggy jewel
#

ohk

#

can i remove all the entries in it

#

@radiant elbow

radiant elbow
#

Sure, that's just an UPDATE statement.

lethal depot
#

quick question, ^ comfybot=> SELECT num_votes FROM INFORMATION_SCHEMA.COLUMNS; ERROR: column "num_votes" does not exist LINE 1: SELECT num_votes FROM INFORMATION_SCHEMA.COLUMNS;

      user_id       | num_votes 
--------------------+-----------
 713979128969429012 |          
(1 row)
``` why do i get a column doesnt exist and when i try to select from num_votes in asyncpg i get a undefined column even though the column is there?
#

solved that, didnt fully understand info.schema.columns

hollow moon
#

hi i using sqlite3 i want to create a login data base with two coloms user and password

#

what will sql return when the WHERE requirment is not met?

#

like where username = "johan" and password = "123"

#

what will it return if that username and password is not there in the table?

silent plaza
#

what method are you using ?

#

fetchone() returns None, fetchall() returns an empty list etc.

#

this is documented

hollow moon
silent plaza
hollow moon
#

thx

alpine gazelle
#

why is def not working

solar thicket
#

You'll need to put some code into your login function, at least a temporary pass statement

#

Otherwise it'll give you an (indent) error

vale sequoia
#

😆

chrome vapor
#

hey I'm new to databases

#

what am I doing wrong here?

#

I thought that on line 2 is where you specify which columns to change and in VALUES you specify the values to change

indigo flare
#

I am pretty sure you need to use ' instead of "

burnt turret
#

doesn't it depend on the database being used? postgres uses ' but i think mysql doesn't mind either iirc

quaint stream
#

is there anyone that uses replit

frozen quail
#

Should I close cursor after every statement execution?

#

while I operate on DB?

torn sphinx
#
else:
            bal = collection.find(user_ide)

            async for i in bal:
                bal_actual = i["balance"]
                bal_updated = round(bal_actual + suma_daily, 2)

            await collection.update_one({"_id":user_id}, {"$set":{"balance":bal_updated}}, upsert=True)
            await ctx.send(f"**Ai primit {suma_daily} :currency: din daily!**")

TypeError: object AsyncIOMotorCursor can't be used in 'await' expression

#
TypeError: object AsyncIOMotorCursor can't be used in 'await' expression```
#

what

burnt turret
#

either ways, try

bal = await collection.find(user_ide).to_list(length=None)
#

actually you don't need the find query

#

you can directly update, but instead of using $set operator, you'd use $inc

#

inc stands for increment

#

so it'll add the value you pass to it to the existing value

torn sphinx
#

That solved my issue, thanks

simple moth
#

What a pythonist should know about DBs? I'm still managing with the concept of selects, joins, where and aggregations, but I feel my foundations are shakey. What are your favorite SQL exercise websites? Preferably Oracle.

austere portal
#

In the mute command for my discord bot I have this: append_member_to_db(member_name=member, member_id=member.id) (i am importing this above), but when I use that command I get this error: InterfaceError: Error binding parameter 1 - probably unsupported type.what do they mean by probably unsupported type.?. Thank you

burnt turret
#

you need to show the query, but #databases message i'm guessing something like this is what is going wrong for you too

flint wolf
#

@simple moth Go with sqlzoo (https://sqlzoo.net/). Covers pretty much everything from basic joins to more fancy stuff

simple moth
flint wolf
austere portal
foggy iron
#

some1 here understand pandas librarie?

torn sphinx
#

Hiya

#

Can someone explain me what is weak entity in databases?

austere portal
torn sphinx
#

@austere portal your error says you are giving wrong type so then give the correct type

burnt turret
#

if your column is supposed to be storing IDs, use member.id in your query instead of member @austere portal

austere portal
#

Thanks, I just specified the arg type: append_member_to_db(member_name=str(member_username), member_id=int(member_id))

burnt turret
#

if this is a discord bot there isn't much point storing usernames though

#

the username can change

#

the ID won't

#
  • if you have the ID, you can get the username and other details at anytime
austere portal
burnt turret
#

aiosqlite is asynchronous, sqlite is synchronous

#

meaning if you use sqlite, the database calls will be blocking

#

and your bot will freeze for the time that it is interacting with the database @austere portal

torn sphinx
autumn epoch
#

What would be the best api to get a bunch of images of that precise thing. I know that there is a google images api, but google images is not as relevant as I want it to be. I am trying to make a command that pulls an image of that certain thing.

torn sphinx
#
async for i2 in result2:
  if i2 == None:
    ctx.send()

How can i do to send something if find returns nothing in mongo

#

with "None" doesn't work

#

nvm

#

forgot that count_documents exists

novel cliff
#

any sql debugger got a set of code for yaal

torn sphinx
#

Hello, I'm looking for a phytoneer or pythonistas that could give me free tutoring. Covid has changed the way we look at the world and therefore I am learning programming to make a career change. Your efforts will not go to waste and I'm highly motivated in learning and studying which will make it easier for you to teach me.

The benefits you will get is learning how to teach and tutor with a highly willing, understanding, and adaptable student. If you're one of those rare people that values knowledge and wisdom then you shall receive it in abundance from me in return for your knowledge.

Please contact me trough PM.

chrome vapor
#

I'm trying to use postgresql in pycharm, I've connected it but nothing is showing up under schemas

ancient fog
#

is there a way i can make an empty table in sqlite3?

thorn nymph
#

guys how can i check tables in database (pg)

ripe lily
#

how do u plot a roc curve for linear regression?

smoky pendant
#

quite sure when u create a table its empty

#

i mean empty in terms of entries

#

but u will still have the columns that u defined it to have

smoky pendant
#

bc in mysql u cant see tables that u dont have permissions for

chrome vapor
smoky pendant
#

well thats good

solemn root
#

How do I navigate around integrity errors? I feel like I need to have logic saying "if table doesn't exist, create the table, else, update it" but how? I'm not too familiar with databases.

#

It happens on the line where I insert the first row (when running the code more than once)

smoky pendant
#

that prob most means there is like a column that must be unique like primary key and u inserted sth that was a repeat

solemn root
#

Also, Autoincrement doesn't seem to work how it's supposed to. (if I remove the manual incrementing I declare, it complains about not having enough values)

smoky pendant
#

if ur auto incrementing i dont think u need to manually insert a PK

solemn root
smoky pendant
#

that doesnt look right

#

u dont pass the literal id into values

#

its like usually INSERT INTO tinker (user_cash, user_token) VALUES (3,5);

inland remnant
#

How do I check if a user has a value in JSON? as there can't be duplicates

{
    "692380305805541430": 123,
    "786098988755320852": 123
}
``` I need to avoid this (they both cant have 123)
#

ping if u can help

solemn root
inland remnant
#

:l

smoky pendant
#

one way is to subquery

solemn root
#

I have to check if discord users have interacted with the bot (which is what I need the database for) before, and only create a new set of rows specific to that user, on the first bot command that user sends.

smoky pendant
#

yeah u will have to do a search than check then insert

solemn root
#

So, only create a database entry on first user --> bot interaction, then update their entry on every future bot command they send

smoky pendant
#

yeah that seems to work

shell ocean
#

bump
@inland remnant parse the JSON and create a counter of values

lethal depot
#
  File "/home/admin/.local/lib/python3.7/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/admin/testcomf/cogs/votes.py", line 36, in votes
    res = await con.fetch('SELECT num_votes FROM votes WHERE user_id = $1', user.id)
  File "/home/admin/.local/lib/python3.7/site-packages/asyncpg/connection.py", line 443, in fetch
    return await self._execute(query, args, 0, timeout)
  File "/home/admin/.local/lib/python3.7/site-packages/asyncpg/connection.py", line 1446, in _execute
    query, args, limit, timeout, return_status=return_status)
  File "/home/admin/.local/lib/python3.7/site-packages/asyncpg/connection.py", line 1454, in __execute
    return await self._do_execute(query, executor, timeout)
  File "/home/admin/.local/lib/python3.7/site-packages/asyncpg/connection.py", line 1466, in _do_execute
    stmt = await self._get_statement(query, None)
  File "/home/admin/.local/lib/python3.7/site-packages/asyncpg/connection.py", line 351, in _get_statement
    statement = await self._protocol.prepare(stmt_name, query, timeout)
  File "asyncpg/protocol/protocol.pyx", line 163, in prepare
asyncpg.exceptions.UndefinedColumnError: column "num_votes" does not exist

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/admin/.local/lib/python3.7/site-packages/discord/ext/commands/bot.py", line 902, in invoke
    await ctx.command.invoke(ctx)
  File "/home/admin/.local/lib/python3.7/site-packages/discord/ext/commands/core.py", line 864, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/admin/.local/lib/python3.7/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UndefinedColumnError: column "num_votes" does not exist```
#

im 100 hundred percent sure im in the right db

#
;
      user_id       | num_votes 
--------------------+-----------
 713979128969429012 |         2
(1 row)

#
    async def votes(self, ctx, user: typing.Optional[discord.Member]):
        if user is None:
            user = ctx.author
        else:
            user = user
        async with self.bot.pg_con.acquire() as con:
            res = await con.fetch('SELECT num_votes FROM votes WHERE user_id = $1', user.id)
        await ctx.send(f'{user.mention} has {res[0][0]} votes')
        
``` the code im using to get that error
smoky pendant
#

well just to completely eliminate the possibility that u connected to the wrong db what db do u specify when u first establish the connection

lethal depot
#
async def create_db_pool():
    bot.pg_con = await asyncpg.create_pool(database='comfybot', user='admin', password='password')
#

bot.loop.create_task(create_db_pool())

#

i even made a whole new table and added a different name for the column but it gave me the same thing

smoky pendant
#

what if u tried SELECT confybot.num_votes FROM votes WHERE user_id = value

#

i feel technically u shouldnt if u connected to right database

#

have u tried running the query from a terminal or sth

feral orbit
#

Hey, I've been using the sqlite3 module for a bit and am now using threads, which is not possible without using locks to safely access the database.

#

I want to stick with core modules, but I'll switch to SQLAlchemy if it lets me keep most of the same commands the same while letting me use threads.

#

Anyone know about switching from sqlite3 to sqlalchemy? Do I have to do the whole ORM song and dance or can I just do execute(query) exactly like before?

smoky pendant
#

well ive used sqlalchemy when i followed a few tutorials and its really similar to how django does stuff

#

so basically u define some models and the models get mapped to database tables

#

also im quite sure sqlite3 has an async lib

#

to deal with transactions that are concurrent

solemn root
#

How can I access my database from my main file if I have all my database create, replace, update, delete code in a separate file? I only want to use my database when I need to, so making calls to it seems more effective than implementing redundant code.

smoky pendant
#

import it?

solemn root
#

I import the module, then call the module, but that’s where I get an error: ‘module’ object not callable

smoky pendant
#

u cant call the module

#

but u can call stuff inside the module

solemn root
#

how can I call all the code inside the module since I can't call the module then?

smoky pendant
#

its like module.function if u do import module

lethal depot
#

@smoky pendant it worked when i tried that in my code

#

can i do tablename.*?

smoky pendant
#

yeah i think so too

#

but the thing is when u connect to a specific database u shouldnt need to specify the database in the query

solemn root
smoky pendant
#

great

hollow moon
#

hi im new to Django what will happen if i run Django without a virtual environment?

blissful narwhal
#

!warn 605807288489476131 Do not post the same question many times across the server. If you need help, please use our help system #❓|how-to-get-help

delicate fieldBOT
#

:incoming_envelope: :ok_hand: applied warning to @alpine gazelle.

brisk harbor
#

how can i use sqlite3 to check if a value exists in a certain column of a table

flat drift
#

Guys how can i check that a mysql Delete query was successfull?

quartz inlet
#

Hi, I am new to coding and am currently working on a project with Python. Has anyone here ever deployed Python script on AWS lambda?

lilac swift
#

Hi, I'm trying to make a field in my Django model derived from another model. For example, I have integer fields in my profile model titled followers and following, and I'd like to get those values from another model by aggregating (count). This other model stores the relationship of users; i.e. who is following and being followed. How am I supposed to go about and get the count of followers and following of each respective user? Really appreciate the help, I'm just new to the world of Django.

deep maple
#

Hello, I have a sql error, I want to insert the nickname of a person in lowercase but with special characters, mysql does not accept it

pseudo= "".join(char for char in ctx.author.name if ord(char) < 128)
            pseudo = pseudo.replace(" ", "").lower()
            print(pseudo)
            cursor.execute(f"SELECT fullname, id FROM compte WHERE fullname='{pseudo}'")```
error:
```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'x>'' at line 1```
brazen charm
#

you should NEVER be using string formatting with query parameters

burnt turret
austere portal
#

How do I delete a column from a table?

burnt turret
#

syntax varies slightly between databases but i think it should be something like

ALTER TABLE tablename DROP COLUMN columname
#

at least i think that's what it is in postgres

austere portal
austere portal
burnt turret
#

do you want to delete a row?

austere portal
burnt turret
#

that's done with a DELETE statement

DELETE FROM tablename WHERE member_id = <some member id>
austere portal
burnt turret
#

i haven't used either but i don't imagine there's gonna be much difference other than adding awaits before queries

#

i may be wrong though

austere portal
#

Ok, thanks again

deep maple
#

i have this error ```cursor.execute("SELECT fullname, id FROM compte WHERE fullname=?", (pseudo,))
File "/home/pi/.local/lib/python3.7/site-packages/mysql/connector/cursor.py", line 543, in execute
"Not all parameters were used in the SQL statement")
mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/home/pi/.local/lib/python3.7/site-packages/discord/ext/commands/bot.py", line 902, in invoke
await ctx.command.invoke(ctx)
File "/home/pi/.local/lib/python3.7/site-packages/discord/ext/commands/core.py", line 864, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/pi/.local/lib/python3.7/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ProgrammingError: Not all parameters were used in the SQL statement```

#

in

#
cursor.execute("SELECT fullname, id FROM compte WHERE fullname=?", (pseudo,))```
austere portal
#

Hi, I am trying to change my function which is using sqlite to aiosqlite, this is my code:

async def append_muted_member_to_db(member_name, member_id):
    conn = await aiosqlite3.connect("muted_members_db.sqlite3")
    local_time = localtime()
    time_format = "%Y %H:%M:%S"
    current_time = strftime(time_format, local_time)

    command = "INSERT INTO Muted_Members VALUES(?, ?, ?)"
    await conn.execute(command, (current_time, member_name, member_id))
    await conn.commit()
    await conn.close()

and I am using that function like this await append_muted_member_to_db(member_name=str(member), member_id=int(member.id)), but I get this error: Command raised an exception: OperationalError: database is locked, What does it mean by database is locked?. Thank you

mint dagger
#

how do i select a whole row's data when a the rows value = something

burnt turret
#

when the rows value?

#

or some specific column in that row = something?

mint dagger
#

lets say i have a row

Username Password Salt

User1 Pass1 Salt1

how can i get that rows data when salt = Salt1 lets say

burnt turret
#

so, to get everything from a row, you'd specify * in the place you usually write the columns you want, and then you use a WHERE clause to check the condition

SELECT * FROM tablename WHERE salt = "salt1";
mint dagger
#

hmmm, whats the return value type, list?

burnt turret
#

that depends on what method of your db driver you use

#

fetch returns a list of tuples where each tuple is a row,
fetchrow returns the single tuple

#

or something along those lines

mint dagger
#

actually theres no point asking that since im not even using python but this is the only server with a databases chat lol

#

thanks

unique bone
#

select names, works from names, works where names.id = works.id.

select names, works from names a, works b where a.id= b.id

Is this the same thing? here i'm trying to select but what is the difference between them?

austere portal
#

conn = await aiosqlite3.connect("db.sqlite3"), this code isn't doing anything?
shouldn't it make a file named db.sqlite3?.

unique bone
#

Can anyone explain what they mean by

Select a.item_Type

Input Table

ItemType(ItemTypeCode,ItemTypeName,ItemCategoryCode,ItemID)

ItemCategory(ItemCategoryCode,ItemCategoryName,ItemID*)

SQL Query

Select a.Item_Type,a.ItemTypeName,b.ItemCategoryName

from ItemType a ,ItemCategory b

where a.ItemCategoryCode = b.ItemCategoryCode

This statement suppose to display  names of all item types with their category names, is it correct?

#

.

burnt turret
#

are you using a connection pool?

#

oh i seem to have misunderstood the question 😅 i'm sorry, i don't know the answer to this

grim crypt
#

um if passwords are stored in the form of digests and hash function is not reversible, how are passwords still "hacked"?

smoky pendant
#

well its hashed when stored but if ur password itself is weak

smoky pendant
#

and ppl can just guess it

brazen charm
#

a DB get leaked with a bunch of hashes

#

you have things like rainbow tables

grim crypt
#

oh

brazen charm
#

which have a bunch of pre hashed passwords that are known

#

or just brute force

#

any password less than 8 character encrypted in MD5 can now be brute forced in a pretty arbitrary amount of time aswell so things like outdated system leaks give even more commonly used passwords etc...

#

Rainbows tables basically trade Disk space for CPU time

grim crypt
#

ah I see

brazen charm
#

so these things are often massive containing billions of passwords pre-cracked

radiant elbow
#

Which is why salting your hashed passwords with a unique per-user salt is important

grim crypt
#

gotcha :) thx

visual meadow
#

If I wanted to make this game and I wanted all but 2 values to start at 0 what could I do to accomplish that (sqlite3 btw)

mint dagger
#

what should i name my database file?
test.db
test.sqlite
test.mdb
any ideas

#

lol its there a reccomend one for SQLite

brisk harbor
#

does anyone know how i can use INSERT to add both variables and strings to a table

#

in sqlite

#

rn im getting sqlite3.OperationalError: near ".": syntax error

wheat umbra
visual meadow
pure dirge
#

I made a DB in DB Browser, I added data to it with my python script, I can see the data in the table being added. When I try to draw the data from the table it returns error

    c.execute('SELECT * FROM questions_agree')
sqlite3.OperationalError: no such table: questions_agree
visual meadow
#

First check if you made a typo when you did sqlite3.connect then check if you made a typo in dB browser when creating the table

#

And also check if you saved/committed your changes

pure dirge
#
import sqlite3
conn = sqlite3.connect('employee.db')
c = conn.cursor()
c.execute('SELECT * FROM questions_agree')
print(c.fetchone())```
#

I can see the changes in the db when I use DB Browser, but my DB Browser acts a little strangely, I used it to create the table so maybe it some how did something weird I'm not sure.

visual meadow
#

You should be using fetchall() when using SELECT *

pure dirge
#

Like my scraper is saving to the db so I don't see how the table doesn't exist or I don't know how to select it

visual meadow
#

Have you checked if youve committed your changes from the browser

pure dirge
#

from the browser?

visual meadow
#

Yes

#

The db browser

pure dirge
#

my code has commit in it

visual meadow
#

Hmm

#

I don't know then sorry

pure dirge
#

I think my db browser is stupid and i dont know why, even since i install it it crashes if i use drop down menu to change a column type

#

so maybe because i made db in there

#

is there another program to try than db browser

visual meadow
#

You could use it from the command line

pure dirge
#

i made this table and db in db browser where as the other one i had working i created myself with code so thats the only difference i can see

#

so much nicer to have function gui than code everything in python lol

visual meadow
#

I've had to live without a GUI because the stupid db browser crashes when I do anything

pure dirge
#

oh nice you have the same problem

visual meadow
#

Not nice at all acc lemon_sentimental

pure dirge
#

i will try manually coding the entire data and then fetching new data and seeing if i can get it to work lol

visual meadow
#

That should work

#

If anything db browsers probably slow you down

distant mason
#

I have this User Class
class User(db.Model, UserMixin):
And this karma value in it
karma = db.Column(db.Integer, nullable =False, default = 0)

I would like to display the users based on who has the greatest karma
topUsers = User.query(User).order_by(User.karma)
somthing like this where i quesry my database and order by karma. howewer this isnt working. Could anyone please help me please?
This is Using SQL alchemy in python3 flask

visual meadow
#

I've never really done anything to do with your specific issue, I've only really done things such as student databases and currency systems. I haven't done any sort of ordering by karma so I can't really help with that sorry

distant mason
#

Thank you for your help

visual meadow
#

Also, I don't mind being pinged, do it as much as you like!

distant mason
#

thank you very much!!!

#

karma is an integer in my model

visual meadow
#

Is Model part of the sqlite3 db object?

#

!d sqlite3

distant mason
visual meadow
#

Oh, misunderstood, also never used that lol

distant mason
#

lol

crude shard
#

Hi there, from this code, ```py
results=collection.find({})

for r in results:
print(r)

I just wanted to find "skins" under this ```{'_id': ObjectId('600b12179d28138ad857f261'), 'Skin': 'BattleByte', 'source': 5}
{'_id': ObjectId('600b1265e54dd0c00ebf6482'), 'Skin': 'BattleByte', 'source': 5}
{'_id': ObjectId('600b1265e54dd0c00ebf6483'), 'Skin': 'BattleByte', 'source': 5}``` what can I do?
#

Like I just wanted the value of the key "skin"

#

Oh and it is pymongo

#

Mongo DB

dawn cloak
smoky pendant
#

well whats the query contained in ur file?

#

that query might have an issue

worldly plaza
#

Does mongodb have a limited amout of use hours per month?

smoky pendant
#

if ur talking about atlas

#

from what i know its just limited storage for free tier

worldly plaza
#

I need to store like a single file with a bunch of numbers etc. will that use to much storage @smoky pendant

smoky pendant
#

well their free tier has a cap of 500mb

#

so depends how big that file is

torn sphinx
#

is the json format still used in mysql?

#

i kinda just decided to switch from json files to sql

#

and im wondering that

smoky pendant
#

i think its still there

#

but ive read ppl say to avoid that to improve search speed

#

but ive never used it

#

like if i think i have destructured data i just use mongo

torn sphinx
#

whats with mongo

smoky pendant
#

literally json

#

mongodb

torn sphinx
#

wait

#

if its the same format as a json file

smoky pendant
#

yeah

torn sphinx
#

whats the difference between using json and a mongo db

#

.jsom

smoky pendant
#

well json u have to load the entire file

torn sphinx
#

.json

smoky pendant
#

and if its big its gonna take some time

torn sphinx
#

and with mongo?

smoky pendant
#

well technically its not loaded for each individual search

torn sphinx
#

and is it easier to access data too?

smoky pendant
#

and i think mongo supports searching for different parameters

torn sphinx
#

like you dont have to do data[example][example][example]

#

if you dont have to do that each time then im changing my whole code just to adapt it to either sql or mongo

smoky pendant
#

it uses sth called collections

torn sphinx
#

collections?

#

how do they work

smoky pendant
#

tbh im not entirely sure

torn sphinx
#

i will be updating lots of data with my discord bot

#

thats why im asking

#

o ok

#

well from what you just said

#

sounds interesting

#

thanks for your time

#

ill look more into dbs

smoky pendant
#

yeah ive mostly been using sql

torn sphinx
#

o thats why

smoky pendant
#

but apparently ive been introduced to mongo

torn sphinx
#

so what do you recommend? sql or mongo?

smoky pendant
#

or at least something im working on is already using mongo bc of other ppl

torn sphinx
#

just to start with

smoky pendant
#

i mean u choose based on how ur data is shaped

torn sphinx
#

its just dictionaries

smoky pendant
#

i mean if its structured sql is nice

#

if its not really structured mongo or some other non relational db works

torn sphinx
#

wdym by structured

smoky pendant
#

like lets say u have a user

#

or sth

torn sphinx
#

like it follows an order?

smoky pendant
#

it has definative fields

torn sphinx
#

o ok

smoky pendant
#

so its easy to represent in tables

#

im kinda learning about mongodb myself

torn sphinx
#

sure its ok

smoky pendant
#

its different

torn sphinx
#

im gonna watch some tutorials tomorrow because i have been learning discord.py the whole day

#

thanks again

burnt turret
# crude shard Like I just wanted the value of the key "skin"

.find takes two arguments, the first is a filter (mongo will only return those documents where the condition specified in the filter is met) and the second is where you specify what fields you want returned.
In your case when you want every field, you'll leave the first dict empty like you have, and in the second dict you'll specify you only want "skin", like
collection.find({}, {"skin":1, "_id":0, "source":0})
Saying skin: 1 tells mongo that you want that field, and the rest: 0 tells mongo you don't want those

torn sphinx
#

When does limit take place?

#

I know it's at end but what if limit is less than how many rows match where clause? Does it stop after it gets its limit or still applies where to all?

shell ocean
torn sphinx
#

I know what it does

#

I am asking if it stops searching as soon as limit had been reached or if it applies limit at the end result set

torn sphinx
#

"SELECT * FROM server_ranks WHERE server_id=? id=?"

#

how can i run this

#

i want to put 2 parms

#

sqlite3.OperationalError: near "id": syntax error

#

it keeps giving this error

torn sphinx
#

thank you

crude shard
#

Oh wait

#

Omg it worked!

#

Thank you

#

@burnt turret

torn sphinx
#

How can I write a SQL query which checks if a value must be equal to X and another value Y has to be in any of 3 columns?

bleak crown
#

Hi i'm using sqlite and in one of my tables, i did PRIMARY KEY to a column called user_id but instead of that i want it to be not just unique directly but has a limit

#

Like right now if i try to insert the same user_id, it gives unique error right but i want it t o be like user_id is unique after 5 entry

#

It is like counting

#

How can i do this in sqlite?

#

Are there something like

#

PRIMARY KEY (user_id, limit=5) or (user_id, count=5)

naive sandal
#

I have the following code:

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.author == self.bot.user:
            return
        keywords = message.content.lower().split()
        data = await self.db.fetch('SELECT Highlights.keyword, HighlightSubs.user_id FROM Highlights INNER JOIN HighlightSubs ON Highlights.id=HighlightSubs.keyword_id WHERE Highlights.keyword = ANY($1)', keywords)
        tasks = []
        for record in data:
            embed = discord.Embed(title='Highlight!', description=f'[{record["keyword"]}]({message.jump_url})', color=self.bot.color)
            embed.set_author(name=message.author.name, icon_url=str(message.author.avatar_url))
            user = self.bot.get_user(record['user_id'])
            if user != message.author:
                tasks.append(user.send(embed=embed))
        for task in tasks:
            self.bot.loop.create_task(task)
``` and I get the following error: https://paste.pythondiscord.com/wukikulalu.sql
#

I'm using asyncpg

modern parcel
#

do you need to specify NULL/NOT NULL when you have default as a constraint?

crude shard
#

Mate, @burnt turret for py results=collection.find({"_id":2}, {"skin":1,"_id":0}) for r in results: print(r)why is it showing like this?{'skin': 'Nothing'}I want it to just print "nothing"

burnt turret
#

this is because mongodb documents are in JSON format - meaning they're dictionaries

#

i.e key: value pairs

crude shard
#

Oh. I see.

burnt turret
#

if you want just the nothing part, you'd use it like any dictionary in python

crude shard
#

Yes so I have to do r["skin"]

torn sphinx
#

Anyone know if gkrou or the Lufthansa persons are in this server still?

burnt turret
#

yep 👍

crude shard
#

THank you my guy

burnt turret
torn sphinx
#

I've been waiting for reply to my questions for like days now no one replies. 🥺

#

Yeah I ask yesterday also

burnt turret
#

but reading it, wouldn't you just use OR a bunch of times?

torn sphinx
#

That is one but I had also a few others

burnt turret
#

or does the any 3 columns mean it could be from any columns in the table

torn sphinx
#

Yeah I fixed that one btw

#

But thanks

burnt turret
#

oh right 👍

torn sphinx
#

Let me get the other

torn sphinx
burnt turret
#

i don't know enough about DBs to answer either haha I'm sorry

torn sphinx
#

Hmm ok but thanks anyways

jade mulch
#

I am having a problem in here
I have to make a user signup code where every user inputs one username (kinda like reddit) but it is not happening

raw inlet
#

does anyone know winreg

crude shard
#

are the contents for requirements.txt okay?

PyNaCl==1.3.0
pymongo
dnspython==1.16.0
async-timeout==3.0.1``` 
for these headers 
```import discord
import datetime
from discord.ext import commands, tasks
from itertools import cycle
import  pymongo
from pymongo import MongoClient```
agile laurel
#

anyone here experience with MongoDB?

burnt turret
agile laurel
#

Alright

torn sphinx
#

best database to use for a discord bot?

crude shard
#

I just used it

agile laurel
#

yup

#

wait

#

poop

#

u experienced?

crude shard
#

Yes perfecting

#

Ehhhhhhh depends

agile laurel
#

aight

torn sphinx
#

thx

agile laurel
#

might if i dm? @crude shard

crude shard
#

Um please keep it here

agile laurel
#

ok

crude shard
#

Because I learnt what I know from people here.

agile laurel
#

So i am working on a discord bot and i am using data base to store information.
But i am wondering if you could modify information in the cluster using command on discord..

crude shard
#

Yes ofc man

#

lol

agile laurel
#

can you redirect me

#

to example

#

or

#

direction

#

like how do i do that?

crude shard
agile laurel
#

thanks

#

🙂

torn sphinx
#

wait what whats with mongodb

#

they give free hosting

#

but i can host it by myself right?

crude shard
torn sphinx
#

I can host it so just the database

#

they give a limited amount of space

#

tho

#

and i cant find any tutorial to host it locally

crude shard
#

What are you hosting?

torn sphinx
#

dont you need to host the database yourself so that you dont need to pay?

#

im getting confused lol

crude shard
#

You can host for free on heroku

torn sphinx
#

kinda new to this sorry

crude shard
#

It's okay

#

Just give details

#

So I can better understand

torn sphinx
#

ok ok}

#

so heroku

#

ok

crude shard
#

No just tell me what are you developing

torn sphinx
#

o ok

#

i just want to save user data and bot data in a database

#

from a discord bot

#

save, update and read

crude shard
#

And for what do you need to save user data for?

#

To work upon it further?

torn sphinx
#

i gues

#

s

#

thing is i dont really understand databases that much and people just told me that its an upgraded json

#

that doesnt corrupt and its easier to access

crude shard
#

Okay tell me what your bot does.

#

And I'll explain what you can do

torn sphinx
#

ok ok

#

at the moment, saves fictional character details and contains a gallery of pictures from each of them

#

and you can access the galleries

#

and those details

#

just that

#

but im planning to add more

#

inventory system, leveling system, minigames, currency, etc

#

thats basically it

crude shard
#

Yes so use mongo db for storing the details and heroku to host it for free 24/7

torn sphinx
#

will i ever run out of space

burnt turret
torn sphinx
#

what is postgresql

#

ok ok

burnt turret
#

they're both SQL databases

torn sphinx
#

but

#

thing is

#

when i searched for sql

#

i got like 5 results

#

mysql

#

sqllite

#

anasql

burnt turret
#

SQL is the query language

torn sphinx
#

oh ok

burnt turret
#

there are many SQL databases

#

basically relational databases (the ones which use SQL) store data in tables

#

in mongodb there is no structure as such, it's just JSON

#

this lack of structure can be useful, but most use cases can be covered with relational databases

torn sphinx
#

so i should just use mysql?

burnt turret
#

well that's your decision

burnt turret
torn sphinx
#

im just going for sql

#

at this point

burnt turret
#

same applies for mysql, or postgres or almost anything else

torn sphinx
#

where can i find a guide

#

to host it

#

locally

#

or in heroku

burnt turret
#

how are you hosting your bot?

torn sphinx
#

my pc

burnt turret
#

you can just search for how to install mysql

#

it isn't a complicated process, there's an installer and you just follow the steps

torn sphinx
#

is there a ui to manage data easier?

burnt turret
#

for mysql there's something called mysql workbench i think

torn sphinx
#

ooo

glossy cove
burnt turret
#

it'll still be easier to do queries though for more complex stuff, but yes workbench is an option

burnt turret
glossy cove
#

im sorry

#

i will try harder to behave

burnt turret
#

the link just explains why you shouldn't be using f-strings for queries

crude shard
glossy cove
#

i mean that depends entirely on your use case and whether you are accepting user input from anywhere

burnt turret
#

true

glossy cove
#

same could be said of sqlalchemy

#

in a more narrow sense ofc

burnt ginkgo
mint dagger
#

how would one structure an account managing projects DB

my system:
one login table which stores login details
a table for each user with all their accounts

a system that was suggested
one login table which stores login details
one table for every users details

?

torn sphinx
burnt turret
#

making a table for each user is rather wasteful

mint dagger
#

but surely it would be faster with a table for each user since you only need to access one table rather then a table with loads of irrelavent data of other users

#

@burnt turret

burnt ginkgo
#

dont think so

burnt turret
burnt ginkgo
#

joins and foreign keys would be really hard to emulate with such approach

burnt turret
#

yep

mint dagger
torn sphinx
red robin
#

how to create a learderboard from sqlite3 form the highest value to the lower

#

ok

celest zodiac
#

@red robin you'd use ORDER BY in your query, or use an ORM (which is my preferred approach)

red robin
#

yeah

#

but its ouputing like

#

this

#

wait

celest zodiac
#

ORDER BY also takes ASC or DESC to sort ascending or descending. e.g. ORDER BY high_score DESC (high to low)

#

assuming high_score is an integer field; if it's text you'll have different ordering

red robin
#

@celest zodiac id want to be like this [(1, 871812), (4, 148898), (28, 6233), (13, 3266), (27, 2000), (2, 0), (3, 0), (5, 0), (6, 0), (7, 0), (8, 0), (9, 0), (10, 0), (11, 0), (12, 0), (14, 0), (15, 0), (16, 0), (17, 0), (18, 0), (19, 0), (20, 0), (21, 0), (22, 0), (23, 0), (24, 0), (25, 0), (26, 0)]without , and ' ([

celest zodiac
#

then you'd sort by whatever the second column is, descending

red robin
#

and without the oid

celest zodiac
#

the commas and brackets are just the formatting Python applies when you print the results to the console

burnt ginkgo
austere portal
#

What does database is locked mean in sqlite?

red robin
#

ok thx

smoky pendant
rich trout
# austere portal What does `database is locked` mean in sqlite?

It usually means your application is open twice, or you have a database editor with the database file open for writing at the same time your application is trying to open it for writing. Most tools I believe have the option to open for reading which will not raise this error

pine estuary
#

Im fairly new to using databases, I am using mongo db to store some information... So if i wanted to call that information how would i do it and set it into catagories of how i stored it. ex. I put an 'id' in and a name and last name: How will i recall it and put it so i can take the name and put it into id: name and last name

worldly plaza
#

I need to grab data from a database with mongodb then set that data to a variable. What is the syntax to do so?

burnt turret
#

what is the data you want to grab? what does your data look like in your database?
generally the syntax to retrieve data from a mongodb collection is

db.collection.find({key: value})

if you want only one matching document

db.collection.findOne({key: value})
#

note that this is in mongo itself, with pymongo it becomes find_one instead of the camelcase

worldly plaza
#

@burnt turret I tried something like this await self.client.config.find({"prefix": prefix}) but it didn’t work

burnt turret
#

what are client, config ?

worldly plaza
#

It is in a class I have

burnt turret
#

i can't really help without knowing

#

is config the name of the database? or your MotorClient object?

worldly plaza
#

The name of the database is Meko

#

@burnt turret I have this in my on ready function


client.db = client.mongo["Meko"]
    client.config = Document(client.db, "guilds")
burnt turret
#

is "guilds" a collection inside your database?

#

i don't think you need to do that Document( stuff, you can just do client.config = client.db['guilds']

worldly plaza
burnt turret
#

what are you expecting, that isn't happening?

worldly plaza
burnt turret
#

you're using motor? @worldly plaza

worldly plaza
#

No

burnt turret
#

huh, what driver are you using?

worldly plaza
burnt turret
#

no, i am asking what database driver module are you using

worldly plaza
#

@burnt turret I am running Motor nvm

burnt turret
#

you don't await finds

#

it gives you a cursor object

#

you probably want to find_one here

worldly plaza
#

I did await it tho

burnt turret
#

you don't await finds

#

you're not supposed to

worldly plaza
#

@burnt turret ah okay, what do I type if I just want to grab the value which prefix is set to?

burnt turret
#

doing find_one will give you the dict that is stored in your database

#

you can then just use it like a dict and get the prefix from it

worldly plaza
#

@burnt turret but what should I put in place of the prefix telling the bot to select it?

burnt turret
#

show more of the function

#

you probably have stored guild IDs

worldly plaza
burnt turret
#

so you should be querying with that - await collection.find_one({"id" : <guild id>})

deft peak
worldly plaza
burnt turret
#

because you want the prefix for that guild

#

the thing you specify in the dictionary is just a filter, the db will retrieve those documents where that key: value pair exists

worldly plaza
#

Alr

austere portal
deep maple
#

Hello, I'm trying to update a given mysql but I get this error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ProgrammingError: Not all parameters were used in the SQL statement in

cursor.execute ("" "UPDATE users SET bio =? WHERE id = '{ctx.author.id}'" "", (bio,))
conn.commit ()

You know why ?

alpine gazelle
#

shouldnt this technically work?

#

```if username_log + ":" + password_log in f````

weak tinsel
#

i get this error while trying to access a postgre db hosted online

#

what is the problem here?

tame girder
#
def addP(da_uuid):
    rows = cursor.execute("SELECT uuid, joins FROM joinsdatabase").fetchall()
    print(rows)
    for row in cursor:
        if da_uuid in row:
            cursor.execute("UPDATE joinsdatabase SET count = ? WHERE uuid = ?", (int(oldCount) + 1, player_uuid))
        else:
            cursor.execute("INSERT INTO joinsdatabase VALUES ('?', 1)"), (da_uuid)
    connection.commit()```
This code does nothing, I want it to add one to the `joins` value
nocturne yew
#

hi

#

TypeError: not all arguments converted during string formatting

#

why i am getting this error

weak tinsel
#

SELECT * WHERE A=B; should get all entries

torn sphinx
#

can someone help with a single database update (pymongo)
I need to update a number in a dict that is inside of a list, number might be existing so it should increase if exists, set the value if doesn't

#

structure is like that

list = [
  {
    "name":"example",
    "value":10
  },
  {
    "name":"example",
    "value":5
  },
  {...}
]```
#

I want to increase value

burnt turret
#

what do you mean by list?

#

is that how your entire collection looks like?

torn sphinx
#

i couldnt find a way around I think ill insert same dicts over and over and merge values together

#

@burnt turret I edited the code above, if I have two dicts with same "name" values how can I get total of "value"s so it returns 15?

safe robin
#

I am trying to make two tables in a database, and I want to create a foreign key to a non-primary key, but I keep getting error messages. I've been at it for a few hours now haha. It says that the "Foreign key constraint is incorrectly formed". I'm using mysql.

proven arrow
#

@safe robin because you made your foreign key field as unsigned and the column you are referencing is not of this type

safe robin
#

OH, so they have to match exactly

proven arrow
#

yes

safe robin
#

Thanks a lot! You get so blind after working on something for a while.

#

@proven arrow haha this is so satisfying, thanks again

pine estuary
#

so im trying to pull info from my mongodb but it pulls None for something i know is strored is there anything visibally wrong?```python
client = MongoClient('connection url')
db = client.gettingStarted
collection = db.Warning

x = await collection.find_one({"id":f"{user.id}"})
await ctx.send(x)```
trim lintel
#

Hello friends.
In my application i would like to make categories for my shop.

#

Now i have already this made but the level is only main category and then subcategory

#

But now there is requirement to have more categories or unlimited categories. One way is to make more tables but this is not so nice to do because it means each time i must make new migrations. What is a good way of model this with as little table as possible but with many categories. Similar like Amazon or ebay where they have many sub levels

proven arrow
#

@trim lintel One way is to have a single categories table. With a single table you can achieve multi level categories. You have the columns, (id, name, description, category_id)
category_id is a nullable foreign key that references the id column on the same categories table.

burnt turret
# torn sphinx <@!271586885346918400> I edited the code above, if I have two dicts with same "n...

okay so you'd need to use mongodb's aggregation pipeline there - i'm not the best to explain how that works but you can read about it here - https://docs.mongodb.com/manual/reference/aggregation/
your query would look something like

db.collection.aggregate({$match: {name: "example"}}, {$group: {_id: 0, sum: {$sum: "$value"}}})

this matches all the documents with the name example, and gives you their sum of values
quote the $ operators and keys, if you're using a driver module

proven arrow
#

So for a parent category the category_id is null as it has no parent. For all descendents they just point to their parent.

trim lintel
#

aha, so this may be a good way to do it actually

#

Thanks i will try that and to see

#

❤️

torpid sky
burnt turret
#

I'm not a bot 😔

torn sphinx
#

copy paste same url you'll get that "embed"

normal oyster
burnt turret
#

Oh that's because of mongodbs site haha

torpid sky
#

srry just... Discord TOS ;-;

rain plank
normal oyster
#

oh yea lol

south cobalt
#

"I want to merge 4 pandas dataframes but I want to merge them in the order of the first column of each data frame then the second columns and so fourth for an arbitrary amount of columns is there a clean way to do this?
it looks like merge or join just appends the columns onto the end"

#

so the new dataframe would be something like this is the original dataframes were DFa DFb & DFc

col1a col1b col1c col2a col2b col2c col3a col3b col3c

torn sphinx
#
#globals   
ipaddress = get('https://api.ipify.org').text
hardwareid = ""





def LoginMenu():
    print("[!] Type 1 to Login || Type 2 to Signup")
    home = input("[>] ")
    if home == "1":
        login(ip)    
    elif home == "2":
        regi(ip)


#

Where would i get the hwid

#

this isd uised for database entry

weak tinsel
#

i get this error while trying to access a postgre db hosted online

solemn root
#

How can I make this dynamic? (Tied to variables instead of static values)
sql_command = """INSERT INTO tinker (user_cash, user_token) VALUES (3, 5);"""

#

I want the 3 and 5 to be dynamic variables that come from my main file and change instead of flat values defined in the same file I have this (not main.py).

#

I want something like this:
sql_command = """INSERT INTO tinker (user_cash, user_token) VALUES (myPurse, user.id);"""

#

^That doesn't work though due to circular import

lavish narwhal
#

Does anyone know how I can retrieve duplicate entries with peewee? (Python Library for SQLite) Right now when fetching an entry, it only brings up the first one it finds.

#
databaseData = [database.MRP_Blacklist_Data.DiscUsername, database.MRP_Blacklist_Data.DiscID, database.MRP_Blacklist_Data.Gamertag, database.MRP_Blacklist_Data.BannedFrom, database.MRP_Blacklist_Data.KnownAlts, database.MRP_Blacklist_Data.ReasonforBan, database.MRP_Blacklist_Data.DateofIncident, database.MRP_Blacklist_Data.TypeofBan, database.MRP_Blacklist_Data.DatetheBanEnds]
        for data in databaseData:
            try:
                q: database.MRP_Blacklist_Data = database.MRP_Blacklist_Data.select().where(data == string).get()
            except:
                continue
            else:
                dataFound = True
                break

This is what I have so far, but it doesn't bring up duplicates

knotty solar
#

can anyone help me with a sqllite3 problem if i put it into a help channel?