#databases

1 messages · Page 152 of 1

elder elk
#
insertquery5 = '''UPDATE soilhealth.fertcom SET 
                    furt_comb_two_name = %s,
                    furt_comb_two_quantity = %s 
                    WHERE shc_no = %s and sr_no= %s  and furt_comb_one_name= %s;'''


                    record_to_insert = [Furt_Comb_Name_Two,
                                        Furt_Comb_Quantity_Two,
                                        SHC_No,SrNo,Furt_Comb_Name]

                    #cursor.execute(insertquery5, record_to_insert)
                    execute_batch(cursor,insertquery5, record_to_insert)

                    connection.commit()
#

throws error like this

#

Failed to insert record into FertRecommandation table One 'int' object does not support indexing
Failed to insert record into FertRecommandation table Two string index out of range
Failed to insert record into FertRecommandation table One 'int' object does not support indexing
Failed to insert record into FertRecommandation table Two not all arguments converted during string formatting

#

where I'm making mistake, please help

#

**where I'm making mistake, please help**

proven arrow
#

From the error its seems you are only supplying a single list.

elder elk
#

please explain in details I'm new to this

#

@proven arrow

torn sphinx
#

Hello, does anyone know why i get a interactionerror here?

    @cog_ext.cog_slash(name="test", guild_ids=slash_ids)
    @commands.is_owner()
    async def test(self, ctx):

        try:

            if ctx.author.id not in premiumusers.values():
                return await ctx.send(f"{ctx.author.mention} you are not stored into premium users so you cant use this command!")

            if ctx.author.id in premiumusers.values():
                return await ctx.send("You are a premium member!")

        except pymongo.errors.DuplicateKeyError:
            await ctx.send("Are your joking? This Member is alredy a Premium User!")
#

using MongoDB

proven arrow
#

Execute batch execute the sql query several times, against all parameters set found in the args list. So if you want to insert two rows, args list needs to be a for example a list, with 2 sublists.

cursor = conn.cursor()

apple_fruit = [1, "Apple"]
orange_fruit = [2, "Orange"]

# list with sublists
argslist = [apple_fruit, orange_fruit] 

execute_batch(cursor, "INSERT INTO fruits (id, name) VALUES (%s, %s)", argslist)
conn.commit()

@elder elk

dusk junco
#

Hello, I'm getting the following error ERROR: there is no unique constraint matching given keys for referenced table "pipeline" when trying to create these tables below. DO I need to include a primary key on PipelineID?


CREATE TABLE IF NOT EXISTS
GITGROUP
(
    ID int PRIMARY KEY NOT NULL,
    Web_url varchar(255) UNIQUE NOT NULL,
    GName varchar(50) DEFAULT NULL
);

--#################################################################

CREATE TABLE IF NOT EXISTS
GITPROJECT
(
    ID int PRIMARY KEY NOT NULL,
    PName varchar(140) NOT NULL,
    GroupID int,
    PDescription varchar(255) DEFAULT NULL,
    Web_url varchar(255) NOT NULL UNIQUE,
    Pstatus varchar(50) DEFAULT NULL,
    FOREIGN KEY (GroupID) REFERENCES GITGROUP (ID)
);


--#################################################################


CREATE TABLE IF NOT EXISTS
PIPELINE
(
    ID int NOT NULL,
    PStatus varchar(50) DEFAULT NULL,
    Web_url varchar(255),
    ProjectID int NOT NULL,
    Start_time date,
    End_time date,
    FOREIGN KEY (ProjectID) REFERENCES GITPROJECT (ID),
    UNIQUE (ID, ProjectID)
);

CREATE TABLE IF NOT EXISTS
JOBS
(
    JobID int NOT NULL,
    PipelineID int NOT NULL,
    Web_url varchar(255),
    job_status varchar(50) DEFAULT NULL,
    FOREIGN KEY (PipelineID) REFERENCES PIPELINE (ID),
    UNIQUE (JobID, PipelineID)
);
torn sphinx
#

this error is not related to the slashcommands or discord.py its something with MongoDb and i know that i do anything wrong here not a issure with MongoDB itself

elder elk
#

please correct it code if possible @proven arrow

proven arrow
#

You can set it as primary key

elder elk
#

I'm little bit confuse,can you please edit one line for me as reference

#

@proven arrow

elder elk
proven arrow
# elder elk I'm little bit confuse,can you please edit one line for me as reference

execute_batch should be outside the for loop.
Inside the for loop you just need to append to your args list.

argslist = []

for dirpath,dirname,filenames in os.walk(filePath):
  for file in filenames:
    ....
    for eachCard in contents:
        ....
        record_to_insert = [Test_Parameter_Id,Test_Parameter_Name,Test_Value,Unit,
                              Rating,SHC_No,Soil_Sample_No,District_Name]
        argslist.append(record_to_insert)

# outside loop
cursor = conn.cursor()

execute_batch(cursor, "INSERT INTO soilhealth.soiltestresult(testparamid,testparamname,testvalue,unit,rating,shc_no,soil_sample_no,district) VALUES (%s,%s,%s,%s, %s,%s,%s,%s)", argslist)

conn.commit()
#

You should be able to figure the rest out now

elder elk
#

thank you so much @proven arrow , I will try it bro

tight smelt
#

its a currency system and its a public bot

digital bronze
#

Would it be better to create additional identical tables for guild data (table name the guild ID) or just have massive tables with a guild ID section to parse through? I think it'd be better with the tables way since then to select user info you just go to SELECT * FROM 1234-user_info; or something and you'll have guild 1234's info instead of doing SELECT * FROM user_info WHERE guild_id = 1234.

harsh pulsar
#

the latter means that you don't have to modify the database schema when you add or remove a guild

#

that's a big advantage imo

#

you can create an index on the guild_id field if queries get slow

torn sphinx
#

anyone knows a solution there:

An exception has occurred while executing command `test`:
Traceback (most recent call last):
  File "D:\Downloads\Python\python 3.8.7\lib\site-packages\discord_slash\client.py", line 744, in invoke_command
    await coro
  File "D:\Downloads\Python\python 3.8.7\lib\site-packages\discord_slash\model.py", line 227, in invoke
    return await self.func(self.cog, *args, **kwargs)
  File "D:\my_python_projects\MongoDB Test\Cogs\music.py", line 472, in test
    if ctx.author.id not in premiumusers:
  File "D:\Downloads\Python\python 3.8.7\lib\site-packages\pymongo\collection.py", line 3432, in __next__
    raise TypeError("'Collection' object is not iterable")
TypeError: 'Collection' object is not iterable
    @cog_ext.cog_slash(name="test", guild_ids=slash_ids)
    async def test(self, ctx):
        await ctx.defer()

        try:

            if ctx.author.id not in premiumusers:
                return await ctx.send(f"{ctx.author.mention} you are not stored into premium users so you cant use this command!")

            if ctx.author.id in premiumusers:
                return await ctx.send("You are a premium member!")

        except pymongo.errors.DuplicateKeyError:
            await ctx.send("Are your joking? This Member is alredy a Premium User!")
elder elk
compact solar
#

someone knows if it's possible to make flask-migrate detect secondary tables declared with "db.Table" ?

south marlin
#

Can someone point me in the right direction when it comes to proper project organizing for SQLAlchemy?

digital bronze
serene pivot
digital bronze
#

How do I use it though? No idea what indexes are.

#

(Just need a basic thing, I can figure out the rest myself)

serene pivot
#

indexes are for decreasing query times.

#

they can dramatically increase performance by avoiding sequential scans on the tables.

digital bronze
#

So if I did

CREATE INDEX 1234-user_info ON user_info(guild_id);

Then it'd be faster to get something like:

SELECT * FROM user_info WHERE guild_id = 1234;

??

hexed estuary
#

If a column isn't an index one, the only way to run a SELECT by that column is by scanning every single record and checking if that column's value is the one you need

compact solar
#

great, i just accidentally dropped all tables on a database at work.. and don't have permission to restore the backup.

serene pivot
#

Here's my issue, my table schema is as follows

+----+--------------------+--------------------+---------+----------------------------+
| id |     server_id      |     channel_id     | command |         insertion          |
+----+--------------------+--------------------+---------+----------------------------+
| 1  |       BIGINT       |       BIGINT       |  TEXT   |         TIMESTAMP          |
+----+--------------------+--------------------+---------+----------------------------+

I'm trying to get this result from selecting the entire table

+--------------------+--------------------------------------------------------------------
|     server_id      |                           result                                  |
+--------------------+--------------------------------------------------------------------
|      BIGINT        | {channel_id: ['string','string'], channel_id_2, ['more_strings']} |
+--------------------+--------------------------------------------------------------------
#

so far, I've only been able to get this as a result

#
+--------------------+---------------------------------------------------------------------------------------------------------------+
|     server_id      |                                                   array_agg                                                   |
+--------------------+---------------------------------------------------------------------------------------------------------------+
| 805638877762420786 | [['805638877762420789', 'avgping'], ['805638877762420789', 'replytime'], ['808425536519012402', 'replytime']] |
+--------------------+---------------------------------------------------------------------------------------------------------------+
#

using this query ```sql
SELECT server_id, array_agg(array[channel_id::TEXT, command]) FROM command_config GROUP BY server_id;

#

granted I could use some simple python after selecting to put it into the format I need, but is there a better way to do this inside of postgres?

harsh pulsar
serene pivot
compact solar
#

there was a backup taken just 2 hours before so should be ok. not sure why i have that ability.. that app using the db is not developed by me.. i'm just getting data from it as a secondary binding in my Flask app and had no idea flask would drop both my primary and secondary binding

harsh pulsar
#

yeah, seems like a good time to double check your permissions

#

flask shouldn't have any database access at all.. sqlalchemy?

compact solar
#

yes

#

just a stupid mistake, but it could cost a few hours of work depending on how fast it's restored...

harsh pulsar
#

@serene pivot ```sql
SELECT
server_id,
json_build_object((array_agg(channel_id))[1]::TEXT, array_agg(command))
FROM
command_config
GROUP BY server_id;

#

there might be a better way to get the distinct channel id here

serene pivot
#

oo yes that's perfect. I got this as the result.

+--------------------+--------------------------------------------------------------+
|     server_id      |                      json_build_object                       |
+--------------------+--------------------------------------------------------------+
| 805638877762420786 | {"805638877762420789" : ["avgping","replytime","replytime"]} |
+--------------------+--------------------------------------------------------------+ 
``` I just need to figure out how to select for all channel ids.
harsh pulsar
#

what do you mean by this?

select for all channel ids.

serene pivot
#

I should clarify. I'm trying to load the entire table into a defaultdict(dict)
the structure would be

# Server ID
805638877762420786: {
  # Channel IDs.       # List of commands
  805638877762420789: ['ping']
  808425536519012402: ['replytime', 'avgping']
} 
#

so each channel would point to a list of commands. And I would get that list from a query like this.

SELECT channel_id, ARRAY_AGG(command)
FROM command_config
GROUP BY channel_id;
#

@harsh pulsar
So that query ^ would return something like this

+--------------------+--------------------------+
|     channel_id     |        array_agg         |
+--------------------+--------------------------+
| 808425536519012402 |      ['replytime']       |
| 805638877762420789 | ['avgping', 'replytime'] |
+--------------------+--------------------------+
``` and my goal would be to have each server ID point to those records for the respective channels
harsh pulsar
#

so you want to do the entire thing in postgres and not in python?

serene pivot
harsh pulsar
#

yeah i think it would get ugly

#

if postgres had a first() aggregation function it'd be easier

#

i don't really understand why this is so hard across all databases

#

there must be some implementation reason why

#

oh this isnt bad

#

well its not great but its not bad

#

@serene pivot ```sql
SELECT
json_build_object(
t1.server_id,
array_agg(t1.channel_obj)
) server_obj
FROM
(
SELECT
cc.server_id,
json_build_object(
cc.channel_id,
array_agg(cc.command)
) channel_obj
FROM command_config cc
GROUP BY server_id, channel_id
) t1
GROUP BY t1.server_id

#

ah not quite

#
-- https://dba.stackexchange.com/a/269321/105807
CREATE AGGREGATE jsonb_object_concat_agg(jsonb) (
  SFUNC = 'jsonb_concat',
  STYPE = jsonb,
  INITCOND = '{}'
);

SELECT
  jsonb_build_object(
    t1.server_id,
    jsonb_object_concat_agg(t1.channel_obj)
  ) server_obj
FROM
(
  SELECT
    cc.server_id,
    jsonb_build_object(
      cc.channel_id,
      jsonb_agg(cc.command)
    ) channel_obj
  FROM command_config cc
  GROUP BY server_id, channel_id
) t1
GROUP BY t1.server_id;

it's definitely approaching "ugly" now

#

probably still more efficient to compute than doing it in python, although you still have to actually get the data back to python over the network

#

probably not that much more efficient than just select server_id, channel_id, command and looping

crisp flint
#

import.sys from file

#

d

crisp flint
#

me too

#

thx

#

wow column

serene pivot
#

wow thank you so much salt that works like magic. Really appreciate your time.

south marlin
#

Do we really need to use psycopg2 with SQLAlchemy?

#

It looks like I was able to do CRUD without using psycopg2

fierce sand
#

:-) im going to make simple cloud

#

And make some sweet sweet e-cash out of it

upper basin
#

so ive got 2 queries,

select rank,threestars+fourstars+fivestars from(select users.*, rank() over (order by threestars+fourstars+fivestars desc) as rank from users) users where userid = {user.id}

and

select userid,threestars+fourstars+fivestars as wishcount from users where wishcount <= ? order by wishcount desc LIMIT ?

is there any way to merge these 2 queries into 1?

#

for more context,

create table if not exists users(
  userid int,
  threestars int,
  fourstars int,
  fivestars int)
tranquil totem
#

How do you see if a collection exists in database in pymongo?

#

@quick bloom could you help me with the database part pls?

burnt turret
#

use db.list_collection_names with a filter that will match for the specified collection name

tranquil totem
#

oh

#

okay

fierce sand
#

How do i edit/write a text to .txt file but using string

#

fh = write()
^ doesn't work with string so i cant save string

tranquil totem
#

I get this error :/```py
Ignoring exception in command afk:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/CaliberBot/cogs/afk.py", line 24, in afk
await server_collection.insert_one(post)
AttributeError: '_asyncio.Future' object has no attribute 'insert_one'

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

Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 902, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 864, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: '_asyncio.Future' object has no attribute 'insert_one'
Future exception was never retrieved
future: <Future finished exception=TypeError('filter must be an instance of dict, bson.son.SON, or any other type that inherits from collections.Mapping')>
Traceback (most recent call last):
File "/usr/lib/python3.8/concurrent/futures/thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/database.py", line 857, in list_collection_names
common.validate_is_mapping("filter", filter)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/common.py", line 494, in validate_is_mapping
raise TypeError("%s must be an instance of dict, bson.son.SON, or "
TypeError: filter must be an instance of dict, bson.son.SON, or any other type that inherits from collections.Mapping

fierce sand
#

Lot of error lemon_eyes

vale pebble
#

@fierce sand
with {'nameoffile.txt'} .open(mode='w') as file:
file.write('String to write' )

#
  • above is used if it is a Path object.
    if not, use open(nameoffile.txt,mode='w')
fierce sand
#

Ok

lapis snow
#

No

grim vault
#

I would make three tables. One for users, one for guilds and one to join them. You can have multiple guilds and a user can be joined with many guilds. It's called a n:m relation between user and guild.

CREATE TABLE User
(
  user_id INTEGER PRIMARY KEY,
  -- additional columns for general user info
);

CREATE TABLE Guild
(
  guild_id INTEGER PRIMARY KEY,
  -- additional columns for general guild info
);

CREATE TABLE UserGuild
(
  user_id INTEGER NOT NULL,
  guild_id INTEGER NOT NULL,
  -- additional columns for user info per guild

  PRIMARY KEY (user_id, guild_id),

  FOREIGN KEY (user_id) REFERENCES User(user_id)
    ON UPDATE CASCADE ON DELETE CASCADE,
  FOREIGN KEY (guild_id) REFERENCES Guild(guild_id)
    ON UPDATE CASCADE ON DELETE RESTRICT
);
CREATE INDEX fk_guild_id ON UserGuild(guild_id);

-- select all user of a guild with all info
SELECT *
  FROM User
  JOIN UserGuild ON UserGuild.user_id = User.user_id
 WHERE UserGuild.guild_id = 1234
;
torn sphinx
#

Hello, does anyone know how i can loop if a value is in premiumusers and if it is then it run a code if not it run another code? i got following code so far but i dont know what this will return like True or False or something else. if someone knows what it will return then i easy can do it by my own.
Here is the code where i dont know what it will return:

premiumusers.find_one(member.id)
tight smelt
#

{
"perma_blacklisted" = []

"week_blacklist" = []
}

#

is that how you use json

umbral jungle
#

just make perm_blacklist.json and when you load the cog

tight smelt
#

yea im not gonna make a new cog

#

but let me read

umbral jungle
#

do it in main file no issue

#

just remove self

tight smelt
#

mk

#

btw

#

im appending

#

to a list

#

so i dont think i will dump

umbral jungle
#

make 2 jsons

tight smelt
#

why?

#

eh whatever

wet stump
#

Hello help me pls

#
select account_id, top 5 device_brand, count(device_brand)
from exaster
group by device_type
#

Not works well for condition: Select currently active clients and pick up TOP5 device brands by each phone type. Please provide the result in one single query.

tight smelt
#

@umbral jungle

#

what does that mean?

wet stump
#

Hello

tight smelt
#

yea

#

i thought

#

lol

#
 if duration == 'perma':
            with open(r"json/perm_blacklist.json",'r') as f:
                perm_blacklist = json.load(f) 
                perm_blacklist[str(user.id)] = user
                with open("json/prefixes.json","w") as f:
                    json.dump(perm_blacklist,f,indent=4)
                await ctx.send(f"`{user}` has been permanently blacklisted.")   ```
#

the file:

{
    "perma_blacklisted": []

}```
#

not workign

#

no error

#

not sending a message

grim vault
#
  1. "perma_blacklisted": [] means it's a list, but perm_blacklist[str(user.id)] = user is for dictionaries. This should fail with an error. edit: I just saw that perm_blacklist is a dictionary, sorry about that.
  2. You use different filenames for reading and writing and you write inside the read (the with statements should have the same indent).
rustic osprey
#

Hey, I am trying to save user ids to a database. im saving them using this code and it works. the id's are correctly commited.

def subscribe(userid):
    importusers()
    if str(userid) not in allusers:
        allusers.append(userid)
        sql = "INSERT INTO registered VALUES (%s, %s)"
        val = userid, True
        try:
            mycursor.execute(sql, val)
            mydb.commit()

They come back like this: 123456

But when i read them with this code:

def importusers():
    mycursor.execute('SELECT userid FROM registered')
    sqlqry = mycursor.fetchall()
    for row in sqlqry:
        print(row)
    return sqlqry

They come back as
(123456,)
(123456,)

#

any idea why?

quick bloom
proven arrow
#

And so you getting a tuple back

torn sphinx
#
SELECT productID
FROM Products
WHERE Products like 'chee[s,z]e';```
#

is this correct?

#

if i want to find cheese/ cheeze

potent spoke
#

i am getting pymongo.errors.ServerSelectionTimeoutError while trying to connect mongoDb to my poython code. can anyone please help?

torn sphinx
#

anyone know why the bot is still allowing users playnow command after i revoked the premiumstatus from them (delete from Database)?

Link: https://pastebin.com/MugCmUFZ
Password: Bv1PxgRdBn

proven arrow
torn sphinx
#

SQL query to retrieve the productID of products which have a productName that contains the word cheese (or cheeze).

#

using regex

proven arrow
#

That doesn’t say which database

#

The [] won’t work in all databases for the LIKE pattern matching. I know Sql server supports it but not sure other vendors. In which case you can use the underscore _ although that would allow any character in it’s place meaning ‘Cheele’ would work also. If you want more specific then use regex

nimble wyvern
#

how to check if a field exists in a document in mongodb?

burnt turret
#

you'd use the $exists operator

nimble wyvern
burnt turret
#

🤔

#

you could add some more info to the query that would be specific to that document?

#

collection.findOne({_id: <doc id>, field: {$exists: 1}}

nimble wyvern
#

collection.find({"_id": 0,'date':{"$exists": False}})

burnt turret
#

yeah

nimble wyvern
#

I'm using this it's not giving me anything

burnt turret
#

wdym?

nimble wyvern
#

even if a date exists

burnt turret
#

what does it return?

nimble wyvern
#

<class 'pymongo.cursor.Cursor'>

burnt turret
#

yes find returns a Cursor

#

you're supposed to iterate over it to see the documents it returned

nimble wyvern
#

l = [ i for i in collection.find({"_id": 0,'date':{"$exists": False}})] something like this would be good to be used on if statement
I want to check if date exists or not

  1. if doesn't exist create a new one
  2. else check the date with some value and makes changes
#

@burnt turret

#

srry for pinging lol

burnt turret
#

why are you using find here instead of find_one?

nimble wyvern
burnt turret
#

right

#

what do you get with the current code?

#

is the list empty or something?

nimble wyvern
#

yes the list empty so i can use it as a falsy value

burnt turret
#

right

#

wait so whats the issue lol

nimble wyvern
#

I wanted to know if there's a better way to do this like from the query itself

#

condition within the query like case 1 do this and case 2 do that

burnt turret
#

ah

#

if you only had to do option 1 in that, you could've done an upsert but i see that's not an option

#

i don't know of a way you could do that in the query itself

#

actually brb

burnt turret
nimble wyvern
burnt turret
#

there might be some way that i don't know of, but the easiest would be just using python here i guess

nimble wyvern
#

oh ok thanks dude

fierce sand
#

i made a file that write the database program again (rewrite) incase someone somewhy edit the file

wooden basin
#

hello, i have this problem and i dont know how to solve it: psycopg2.errors.OutOfMemory: out of memory DETAIL: Failed on request of size 448.

rustic osprey
# proven arrow And so you getting a tuple back

thanks. that was a push in the right direction. i do it like this now:

def importusers():
    mycursor.execute('SELECT userid FROM registered')
    sqlqry = mycursor.fetchall()
    allusers = [row[0] for row in sqlqry]
    return allusers
ruby magnet
#

i'm making a sqlite3 controler using python and i'm making the delete data from a table feature, but it says it can't find column, code:

#
def delete_data(table, first_data, first_data_in_row):
    cur = connection.cursor()
    cur.execute('DELETE FROM {} WHERE {}=?;'.format(table, first_data), (first_data_in_row,))

table = input("input table:")
first_data_in_table = input("input first data in the table:")
first_data_in_row = input("input the first data of a row u want to delete")
delete_data(table, first_data_in_table, first_data_in_row)
#

it's not the best interface but it's the only think i can think off

#

when i put in the data it says it didn't find the column and it deleted the whole data in the table

lusty inlet
#

(2) as you're working on this, try printing/logging/viewing the queries you've built before execution. in this case it sounds like first_data didn't properly capture the column you wanted

ruby magnet
#

alr, thx man

torn sphinx
#

Guys I have this huge file with 30k lines and every few hundred lines there is a list that begins with Position and has 100 entries or so

#

then inbetween there is other unrelated info

#

How can I find the lines where the title of the table is

#

I used this but didnt work:

#
file = open(path_to_file, "r")
n = 1
line = []
for line in file.readlines():
    if line == "POSITION                                       TOTAL-FORCE (eV/Angst)":
      print("Line found at ", n)
      line.append(n)
    n += 1
print(len(line)) 
raven trail
#

What is the best way to check if a table exists using Python/SQL query?

#

using PostgreSQL

delicate fieldBOT
#

The with keyword triggers a context manager. Context managers automatically set up and take down data connections, or any other kind of object that implements the magic methods __enter__ and __exit__.

with open("test.txt", "r") as file:
    do_things(file)

The above code automatically closes file when the with block exits, so you never have to manually do a file.close(). Most connection types, including file readers and database connections, support this.

For more information, read the official docs, watch Corey Schafer's context manager video, or see PEP 343.

harsh pulsar
#

also you don't need .readlines to iterate over a file - in fact you probably shouldn't do this

torn sphinx
#

i figured it out

harsh pulsar
#

.readlines reads the entire file into a list; you can just iterate over the file object directly

#

please read the blurb i posted about with open

torn sphinx
#

oh

harsh pulsar
#
lines = []
n = 0
with open(path_to_file, "r") as fp:
    for line in fp:
        if line == "POSITION                                       TOTAL-FORCE (eV/Angst)":
            print("Line found at ", n)
            lines.append(n)
            n += 1
print(len(lines))
torn sphinx
#

so its faster that way?

harsh pulsar
#

this would be a more idiomatic way to write the code

#

its safer (no chance of leaking resources) and more memory efficient

#

good habits are important

torn sphinx
#

yes definitely

#

thank very much

harsh pulsar
#

👍

#

do you want to extract the 100 lines afterwards?

#

you can do it in a single pass over the file

torn sphinx
#

yeah thats exactly what I need to do afterwards

harsh pulsar
#

e.g. if you have a file like this

as;dlf
zxcv

dfvas
START
1
2
3
4
5
END
a;oij
aoi

awino
START
8
9
10
END
ijo
iourtoij
#

you can get all the data between START and END

patent cove
#

so im not good with json, and im trying to get all of the data to append to entrys in my json file.

{
    "entrys": [
           
    ]
}

and rn im completly lost

def save():
    with open("journalEntrys.json",) as json_file:
        maintext = maintextbox.get(1.0, "end-1c")
        nametext = namebox.get(1.0, "end-1c")
        date = datetime.datetime.utcnow()
        date = date.strftime("%m/%d/%Y, %H:%M:%S")
        data = {
            "name": nametext,
            "text": maintext,
            "utc-time": date
        }
        loaded = json.load(json_file)
        for i in loaded["entrys"]:
            print(i)
harsh pulsar
#

btw neither of these are "database" questions

patent cove
#

im getting for i in loaded["entrys"]: KeyError: 'entrys'

harsh pulsar
torn sphinx
#

I was unsure, I did solve part of my problem in one of the help channels

#

but im interested in getting the data between start and end as well

harsh pulsar
#

@patent cove ask this in a help channel too

proven arrow
#

It should have a table called tables.

rustic osprey
#
    if str(userid) in str(allusers):      
        try:
            mycursor.execute("DELETE FROM registered WHERE userid = ", str(userid))

i'm trying to use this to delete a single row where the userid matches. the query works on the mysql console from my python code it seems to skip it. why is this wrong?

harsh pulsar
#

@rustic osprey i assume you have except: after that try?

#

if so, don't do that

#

also what is allusers? a list?

#

str() on a list makes a "pretty" version of the list as a single string

#

it does not turn each element of the list into a string

rustic osprey
#

yeah its a list. i have a debug output before and after that sql query.

#

the one before gets printed, the one after it doesnt

harsh pulsar
#

ok, do you understand the problem with str(allusers)?

rustic osprey
#

kind of.

harsh pulsar
#

!e ```python
allusers = [1234, 5678, 9876]
print(repr(str(allusers)))

delicate fieldBOT
#

@harsh pulsar :white_check_mark: Your eval job has completed with return code 0.

'[1234, 5678, 9876]'
harsh pulsar
#

str(allusers) returns a single string '[1234, 5678, 9876]'

#

this is almost certainly not what you want

rustic osprey
#

the list doesnt have much to do with the sql query. im just syncing the database into that list to quickly check if the id is in there somewhere

harsh pulsar
#

well that could be why it's "python seems to skip it"

#

because your if doesn't work

#

or if it does work sometimes, it's pure luck

rustic osprey
#

but why does it show the print thats in that if statement?

harsh pulsar
#

because technically the string '1234' is part of the string '[1234, 5678, 9876]' so it kind of works sometimes

#

!e print('1234' in '[1234, 5678, 9876]')

delicate fieldBOT
#

@harsh pulsar :white_check_mark: Your eval job has completed with return code 0.

True
harsh pulsar
#

but fair enough, that isn't this particular problem

#

more likely is that you are abusing except which is causing python to swallow and ignore an error

#

show more of your code if you can

rustic osprey
#
    if str(userid) in str(allchats):      
        try:
            print("this works")
            mycursor.execute("DELETE FROM registered WHERE userid = ", str(userid))
            print('this works too')
            importusers()
            return "ok."
        except
            return 'Cannot delete userid from database.'
    else:
        return 'not registered in database'
#

if i remove the prints it goes directly to except

#

i removed try / except. -> ValueError: Could not process parameters

#

i guess that means the variable is in wrong format?

proven arrow
grim vault
harsh pulsar
#

yep, that's important

barren zinc
#

I would like to download a file and then store it in my own database and then upload it. So i want to get a link so people can download it from my database. Is it possible? I would like to use https://gofile.io/

balmy aspen
harsh pulsar
#

nope, i pinged you. you had suggested using regex for a problem that "Supreme Patriarch" was working on

balmy aspen
#

Aaaaah

#

Yeah i mean, when i think about matching some pattern i go to regex. He needed that so thats why i suggested him to use regex

harsh pulsar
#

i wonder if this particular regex would be faster than looping linewise in python

#

doesn't seem like there would be much backtracking as long as the data meets the assumptions

torn sphinx
#

how does relational DB sharding (MySQL, postgres) compare to noSQL db sharding (like mongoDB)?

#

apparently both support sharding but surely there is a big difference between the two?

copper dragon
#

SQL DBs have structured data while NoSQL are unstructured
SQL have more relationship options(onetoone, manytomany, onetomany, foreignkeys etc) hence better for something like a social media while MongoDB have JSON formatted easy to use and work with data

harsh pulsar
inner veldt
#

Hey guys, does anyone know about any python's packages for rain data and forecasting?

pure sleet
inner veldt
#

thanks!

nimble wyvern
#

how to whitelist my heroku application ip in mongodb atlas?

torn sphinx
#

how do i edit a database using python

#

sql databse

#

How to create a database and learn these codes like SELECT, CREATE, etc?

#

xD

wary nebula
burnt turret
nimble wyvern
#

Gotta add some extra adons to make it satic or something

#

Whitelisted every IP for now 😥

nimble wyvern
burnt turret
#

dunno, haven't tried it

torn sphinx
#

hey guys,
how do you suggest I run my django database migrations when im deploying to google cloud run?
should i add it to the CMD in the Dockerfile?
im using google cloud sql with postgres 13 btw

rancid cloud
#

hey everyone what's the difference between postgresql and mysql in which case is one useful than the other and
which DBMS is used by snapshat

brazen charm
#

which DBMS is used by snapshat

Probably several e.g. Redis / Keydb, Cassandra / Scylla, with some extra relational database aswell

#

as for

between postgresql and mysql
They're both relational SQL databases, however postgres is generally the preferred database in the modern world because it just outperforms MySQL in most cases, has much better SQL standard support and much more utility (MySQL also has several issues like UTF-8 Encoding but thats fixed with something like MariaDB)

rancid cloud
torn sphinx
torn sphinx
#

Some ways they can do this is by using local storage or local device db

sullen wolf
#

How do I make a list in a SQlite DB?

proven arrow
brazen charm
#

the issue is that its not UTF-8 by default 😔

fallow coral
#

absolute noob to databases but im using sqlite3 for a discord.py bot.
is it a bad idea to write a wrapper like this? it seems safer to use a wrapper than to rely on me remembering to open and close the connection every time i write a new function

def conclose(func):
    def wrapper(*args):
        conn = sqlite3.connect(
            str(Path(__file__).resolve().parent)+"/namehere.db")
        c = conn.cursor()
        func(c, *args)
        conn.commit()
        conn.close()
    return wrapper
burnt turret
#

🤔 feels like something that would be neatly done with a context manager

#

i'd thought earlier that using the connection object itself as a context manager would have it close the connection, but that doesn't look like it is the case; looks like it autocommits

#

might be a nice place to use contextlib.closing lemon_thinking

#

!d contextlib.closing

delicate fieldBOT
#

contextlib.closing(thing)```
Return a context manager that closes *thing* upon completion of the block. This is basically equivalent to:

```py
from contextlib import contextmanager

@contextmanager
def closing(thing):
    try:
        yield thing
    finally:
        thing.close()
```...
fallow coral
#

wow i dont understand that lmao

#

i'll have to look into it. Thanks

proven arrow
#

Doesn't sqlite alread support context manager, why make your own?

burnt turret
#

the docs seem to say it won't close the connection

#

it just commits

grim vault
#

The question is if you need to open/close the connection all the time.

torn sphinx
#

Does anyone have any idea how to make editable pages like CMS. What would design look like or how to set this up.

#

Simple cms functionality to use with some pages on a site.

fallow coral
grim vault
#

Okay, with that low traffic it won't hurt the performance much if you open and close it for every sql command. It's just sqlite has some things to do if it opens the database.

proven arrow
torn sphinx
#

Currently we have a homepage and offers page. Content on it is currently coded from the server. Changing this content means i must have to update the code each time, even if its just like text wording change. Client currently has to pay for this, so they want something long term where they can update themselve.

Here is the request they sent me:
An admin user should be able to change content of the home/offers page directly from the Admin portal.
This is for our phase 2 development.

#

For code i will just code it so that for homepage it will know to look for x data, and for offers it will know to look for y data.
Current content is like images for slider, header text etc.

proven arrow
#

So if i understand correctly you just want them to edit the content you have, but not the ability to style/choose its location on page etc?

#

@torn sphinx

torn sphinx
#

Yes

proven arrow
#

That could be achieved with something like this

remote plinth
#

quick question: can we use += in sqlite?

#

like UPDATE .... SET x += 1

remote plinth
#

SET x = x + 1?

#

if no, how can i increment

grim vault
remote plinth
grim vault
remote plinth
#

thanks.

proven arrow
#

@torn sphinx Its what i have in one project. Diagram is self explanatory but pages just stores details of the page (template refers to a file within the code that has code which tells it how to be setup.)
page_contents stores a key value of the content you want for that page.

remote plinth
#

"UPDATE tags SET users = users + 1"

#

would that increment users?

grim vault
#

if it's not null and a number, yes.

#

for ALL entries in tags.

fallow coral
#

is there a wildcard for WHERE? i know its kinda redundant but i have a use for it

harsh pulsar
#

@fallow coral what do you have in mind? hypothetically even

fallow coral
#

i have an existing function which takes in one argument and finds all entries where a given column has that value. It does some other stuff too.

i just realised that the bug staring me in the face was that i used it when i had intended to select from two columns.

if i could have def myfunc(existingArg, newArg="wildcard") then by default i can use the function as it is now, or by passing something to newArg i can specify from a second column too

#

instead of having two nearly identical functions i figure it makes more sense to just use one with an optional arg

harsh pulsar
#

im not entirely sure what you mean by "wildcard" - is this for the LIKE operator?

#

or do you need to construct a sql query for a dynamic set of columns?

#

you might have to just use string interpolation/concatenation for that, unfortunately

#

you can only parameterize "data", not column names or expressions

fallow coral
#

basically, in a function myfunc(existingArg, newArg="wildcard_here") I want to be able to accept any value of name unless i specify a value for newArg;
cursor.execute(f"SELECT * FROM tasks WHERE space="{existingArg}" AND name="{newArg}")

#

it currently works when i dont have newArg=... or AND name=... in there, im not sure what to put as a default for newArg to make it accept any value for name

grim vault
#

I'm doing it like this:

def build_update_stmt(tbl_name, cols, *cols_id):
    return (
        f"UPDATE {tbl_name} SET {'=?,'.join(cols)}=?"
        f" WHERE {'=? AND '.join(cols_id)}=?"
    )

def update_from_dict(tbl_name, upd_colums, **id_colums):
    cols, bind = zip(*[col for col in upd_colums.items()])
    cols_id, bind_id = zip(*[col for col in id_colums.items()])
    bind += bind_id
    stmt = build_update_stmt(tbl_name, cols, *cols_id)
    return stmt, bind

tbl_name = "user"
upd_colums = {"name": "Berndulas", "age": 50}

stmt, bind = update_from_dict(tbl_name, upd_colums, user_id=1, aktive="yes")
print(stmt, bind)

output:

UPDATE user SET name=?,age=? WHERE user_id=? AND aktive=? ('Berndulas', 50, 1, 'yes')```
harsh pulsar
grim vault
#

I can't?

harsh pulsar
#

@grim vault i was replying to the other user

#

you're doing it correctly

#

wcj is not

fallow coral
#

do f-strings misbehave? or is it a best practice thing

harsh pulsar
#

both

#

it's best practice for a reason

#

even if security is not relevant for your use case, escaping is a nightmare and generally not something you want to do manually

#

e.g. for sqlite3

cursor.execute("SELECT * FROM tasks WHERE space=? AND name=?", (existingArg, newArg))
#

consult the docs for your particular sql library for the placeholder style

#

it can be ?, $1, %s, or i think one other option

#

!e ```python
import sqlite3
print(sqlite3.paramstyle)

delicate fieldBOT
#

@harsh pulsar :white_check_mark: Your eval job has completed with return code 0.

qmark
harsh pulsar
fallow coral
#

okay, ill use params if fstrings are an issue

harsh pulsar
#

not just f-strings - any and all string concatenation, interpolation, etc

#

you see how bernudas constructed the sql code, then left ? placeholders for the data?

#

that's the right way to do it

fallow coral
#

okay, cool

fallow coral
harsh pulsar
#

ah, i see

#

no, you'd have to have an if in your python code and 2 different queries, or construct a query like bernudas is doing

#
def myfunc(cursor, arg1, arg2=None):
    query = "SELECT * FROM tasks WHERE space=?"
    params = [arg1]
    if arg2 is not None:
        query += " AND name=?"
        params.append(arg2)
    cursor.execute(query, params)
#

or

def myfunc(cursor, arg1, arg2=None):
    if arg2 is None:
        cursor.execute("SELECT * FROM tasks WHERE space=?", (arg1,))
    else:
        cursor.execute("SELECT * FROM tasks WHERE space=? AND name=?", (arg1, arg2))
fallow coral
#

okay, i'll do it like that if theres no other way

grim vault
#

Or use keyword argument packing.

fallow coral
#

the ? thing works in INSERT INTO table VALUES (?, ? ,?), right?

harsh pulsar
#

yes

fallow coral
#

okay, thanks for your help guys!

nova dawn
#

!e

#

!e

import glob
for file in glob.glob("*"):
  print(file)
#

!e

import glob
for file in glob.glob("/config"):
  print(file)
delicate fieldBOT
#

@nova dawn :warning: Your eval job has completed with return code 0.

[No output]
nova dawn
#

!e

import glob
for file in glob.glob("*"):
  print(file)
delicate fieldBOT
#

@nova dawn :white_check_mark: Your eval job has completed with return code 0.

001 | Pipfile.lock
002 | Pipfile
003 | config
004 | snekbox
005 | user_base
006 | tests
007 | LICENSE
tranquil totem
#

how do you create a new field in an existing document using pymongo?

nova dawn
#

honestly idk lol

#

i usually use sql

#

!e

import os
print(os.cwd())
#

!e

import os
os.system("ls -l -a")
delicate fieldBOT
#

@nova dawn :warning: Your eval job has completed with return code 0.

[No output]
harsh pulsar
tranquil totem
pliant cliff
#

I'm trying to use SQLAlchemy... but it won't create the db :/

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:////tmp/test.db"
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

    def __repr__(self) -> str:
        return '<User %r>' % self.username

then in the terminal... i type:

>>> from app import db
>>> db.create_all()
File "path", line 584, in connect
  return self.dbapi.connect(*cargs, **cparams)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) unable to open database file
(Background on this error at: http://sqlalche.me/e/14/e3q8)
gaunt agate
#

what OS are you using

pliant cliff
#

i saw what happened... there was no tmp folder

#

and I had to use 3 / not 4

#

If only the docs made that clear :/

#

windwos

gaunt agate
#

so does it work for you now?

pliant cliff
#

Yes please

gaunt agate
#

Thats great

harsh pulsar
tranquil totem
#

okay thanks

elder elk
#

somebody please help

#
insertFertComb = '''INSERT INTO soilhealth.test_fertcom(
                    sr_no,furt_comb_one_name,furt_comb_one_quantity,shc_no,
                    soil_sample_no,district)
                    VALUES %s'''

updateFertComb = '''UPDATE soilhealth.test_fertcom SET 
                    furt_comb_two_name = %s,
                    furt_comb_two_quantity = %s 
                    WHERE shc_no = %s and sr_no= %s  and furt_comb_one_name= %s;'''

#

I have two query one is for insert and another for update

#
connection.commit()

print('Inserting Records into DataBase "FertComOne"....')

end_time1 = datetime.now()
print('Duration for Running to all input Village : {}'.format(end_time1 - start_time))

execute_values(cursor,updateFertComb, listFertCombTwo )
connection.commit()

print('Inserting Records into DataBase "FertCombTwo"....')```
#

using execute values of psycopg2 insert query runs fine but for update it shows error

#
ValueError: the query contains more than one '%s' placeholder
#

please suggest correction

red pelican
torn sphinx
#

hey guys,
how do you suggest I run my django database migrations when im deploying to google cloud run?
should i add it to the CMD in the Dockerfile?
im using google cloud sql with postgres 13 btw.

sorry about asking the same question twice. didnt get anyone to reply the first time.

hazy smelt
#

How to fix MySQL connector connection refused

wide hinge
#

Hi, is there anyone have a resource or can explain what is sql GROUPING() function ? ?

eager igloo
#
@commands.Cog.listener()
    async def on_guild_remove(self, guild):
        stats = inviteLogger.find_one({"guild_id" : guild.id})
        if stats == None:
            print("no stats")
        else:
            for i in stats:
                print("here")
                inviteLogger.delete_many(i)`````` File "C:\Users\Stacker 10000\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\Stacker 10000\Desktop\.Penguin-master\penguin-master\cogs\invite_logger.py", line 31, in on_guild_remove
    inviteLogger.delete_many(i)
  File "C:\Users\Stacker 10000\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pymongo\collection.py", line 1283, in delete_many```
#

help

remote plinth
#

uhh can i use cur.fetchall to execute code for ex ```py
cur.fetchall(sql, [ctx.author.id, tag])

instead of
```py
cur.execute(sql, [ctx.author.id, tag])
x = cur.fetchall()
#

??

tranquil totem
#

How can I store data for an afk command?

torn sphinx
#

I wanna connect discord.py to mongodb(PyMongo)! Where do I start from?

novel oak
#

help pls, I have an SQL database for my discord bot organised by users and their XP, and I am using iosqlite, is there any way I could get an specific number of users in the DB (eg: 20) wich have the maximun number in the XP field, I want to make a dashboard of the server users and their levels

harsh pulsar
harsh pulsar
torn sphinx
torn sphinx
#
db = sqlite3.connect('INTRO.db')
                                        c = db.cursor()
                                        c.execute(f"CREATE TABLE IF NOT EXISTS info(name Text, age INTEGER , gender TEXT , location TEXT, hobbies TEXT, memberid INTEGER , membername TEXT)")
                                        c.execute(f"SELECT name ,age , gender , location , hobbies FROM info WHERE memberid={ctx.author.id} and membername='{ctx.author.name}'")
                                        result = c.fetchone()
                                        if result is None:
                                            c.execute(f"INSERT INTO info VALUES ('{name.content}' , {age.content} , '{gender.content}','{location.content}','{hobby.content}', {ctx.author.id} , '{ctx.author.name}')")
                                            db.commit()
                                            db.close()
                                        else:
                                            c.execute(f"UPDATE info SET name ='{name.content}', age={age.content}, gender ='{gender.content}',location='{location.content}',hobbies='{hobby.content}' WHERE memberid={ctx.author.id} and membername='{ctx.author.name}' ")
                                            db.commit()
                                            db.close()```
#

bruh

#

ah so

#

why cant i store xyz' in the db

#

i meant that string with the comma

west furnace
#

as long as you know how they work individually

torn sphinx
candid folio
#

yoo i have a question is it better to use python or C++

#

?

torn sphinx
west furnace
torn sphinx
#

lmao

torn sphinx
#

is this even readable? sorry if it isnt lol

candid folio
#

web*

west furnace
torn sphinx
west furnace
torn sphinx
#

hmm

torn sphinx
#

i sent the code above

rough hearth
torn sphinx
#

i mean if i try storing any string with a ' .. it doesnt store it

west furnace
#

so it probably clashes with that

torn sphinx
#

so how do i fix it lol

torn sphinx
torn sphinx
west furnace
#

\\'

torn sphinx
#

nvm i was wrong

torn sphinx
west furnace
#

the c++ bot lib is not fun

torn sphinx
#

it still doesnt store xy'

west furnace
torn sphinx
#

yesss i did

west furnace
#

idk

#

maybe this is worth a read

torn sphinx
#

ah wait

#

if i try storing xyz''

#

it stores xyz'

#

im confused lol

west furnace
#

okay, well that solves you issue?

torn sphinx
#

look at the last embed.. and the name field

torn sphinx
west furnace
torn sphinx
#

yes only if i input the value as xyz''

west furnace
#

yeah, then just input that

torn sphinx
#

u mean xyz'?

#

thats what im doing

#

it is not working

west furnace
#

from the link I posted

torn sphinx
#

ahh lemme look into it again lol

torn sphinx
#

lemme try

torn sphinx
west furnace
#

np

torn sphinx
#

if u can .. explain with an example : D

torn sphinx
west furnace
#

just import it

torn sphinx
west furnace
#

I'd maybe try

#

print("My name is "vim vim", what's yours")

#

but this is the same as
print(str("My name is ") vim vim str(", what's yours"))

#

because it reads the " not as something to print

#

but as the end of the string

torn sphinx
west furnace
#

like this

#

print("My name is \" vim vim \", what's yours"))

novel oak
# harsh pulsar Can you use `ORDER BY user.xp DESC LIMIT 20`?

I am doing this:

DB = await aiosqlite.connect('UsersIceEmpire.db')
c = await DB.cursor()
await c.execute("SELECT ID FROM UsersDiscordIceEmpire ORDER BY XP ASC")
DashboardXP = await c.fetchmany(10)
print(DashboardXP)
await DB.commit()
await DB.close()
``` but doesn't returns the ids of users in order of more XP to less, it doesn't work the ORDER BY why is this?
west furnace
#

if you need a database

west furnace
#

import shelve

rose parrot
#

@novel oak if you want people with > XP first you should use DESC

torn sphinx
west furnace
#

yes

torn sphinx
#

i see yes!!!!!!

#

the single quote was clashing with the single quote i input into the value

#

i see

torn sphinx
#

u learn something new everyday

torn sphinx
torn sphinx
torn sphinx
west furnace
#

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

torn sphinx
torn sphinx
west furnace
#

leave your bot project to the side for a while

#

and start a new one, where you play around with shelve

torn sphinx
#

I came across DiscordDBPlus, Do you know something about it?

west furnace
#

use a channel to store data

#

yeah no, that's a bad idea

torn sphinx
west furnace
west furnace
#

good luck

torn sphinx
torn sphinx
west furnace
torn sphinx
west furnace
#

np

grim vault
# torn sphinx ```py db = sqlite3.connect('INTRO.db') c...

You really should use the parameter version for sql like:

db = sqlite3.connect('INTRO.db')
c = db.cursor()

sql_stmt = (
    "CREATE TABLE IF NOT EXISTS info"
    " ("
      " name TEXT,"
      " age INTEGER,"
      " gender TEXT,"
      " location TEXT,"
      " hobbies TEXT,"
      " memberid INTEGER,"
      " membername TEXT"
    ")"
)
c.execute(sql_stmt)

sql_stmt = (
    "SELECT name, age, gender, location, hobbies"
     " FROM info"
    " WHERE memberid = ?"
      " AND membername = ?"
)
sql_bind = (ctx.author.id, ctx.author.name)
result = c.execute(sql_stmt, sql_bind).fetchone()
if result is None:
    sql_stmt = "INSERT INTO info VALUES (?, ?, ?, ?, ?, ?, ?)"
else:
    sql_stmt = (
        "UPDATE info"
          " SET name = ?, age = ?, gender = ?, location = ?, hobbies = ?"
        " WHERE memberid = ?"
          " AND membername = ?"
    )

sql_bind = (
    name.content, age.content, gender.content, location.content, hobby.content,
    ctx.author.id, ctx.author.name
)
c.execute(sql_stmt, sql_bind)
db.commit()
db.close()
west furnace
#

yeah, that too

#

I agree

#

you wouldn't have had that problem

#

@torn sphinx

torn sphinx
#

I see

jaunty marsh
#

Hi all. I switch my django database from sqlite to postgres yesterday but now when I add new items the pk ID would be out of sync and throw error "duplicate key value violates unique constraint ... already exists"

#

I found this fix

SELECT setval('*table*_id_seq', (SELECT MAX(id) FROM *table*)+1);
#

But it's only temporary, it'll get out of sync and error again after a while. Is there any permanent way to fix it?

wheat python
#

What do you use for databases when you programm .py
I use .json

jaunty marsh
#

When I populate the database I did

python manage.py loaddata datadump.json
jaunty galleon
#

Anyone knows how to fix PostgreSQL(asyncpg(elephantsql)) TooManyConnectionsError error?

thorn geode
#

Most people tend to use SQL based databases

remote plinth
#

json is not database!

shell ocean
#

JSON is a data format

west furnace
#

hmmmm

#

I guess a json file is maybe

faint maple
#

I use a JSON file as a light db to load in a few objects and save it after making a change to the dict (which isn’t often at all, a few requests per day if that)

quaint ore
wheat python
opal hill
#

What's a good online source to start learning SQL?

vale pebble
opal hill
bold acorn
#

How do I start learning?

grim vault
#

Start reading?

torn sphinx
#

Can we call the shelve module is somewhat same as Json??

supple comet
#
with open('rejected') as f:
    rejected = f.read().split('\n')
cur.execute('UPDATE Drugs SET rejected=1 WHERE (id IN ?)', (rejected, ))

I cannot for the life of me figure out why this is raising sqlite3.OperationalError: near "?": syntax error

tranquil totem
#

error:```py
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "/home/runner/CaliberBot/cogs/afk.py", line 40, in on_message
find_user = await collection.find_one({"_id": message.guild.id})["afk_members"]
TypeError: '_asyncio.Future' object is not subscriptable
Ignoring exception in command afk:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/CaliberBot/cogs/afk.py", line 24, in afk
data = await collection.find_one({"_id": ctx.guild.id})["afk_members"]
TypeError: '_asyncio.Future' object is not subscriptable

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

Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 902, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 864, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: '_asyncio.Future' object is not subscriptable

#

code:```py
@commands.command()
async def afk(self, ctx, status = None):
if (await collection.count_documents({"_id": ctx.guild.id})) == 0:
post = {"_id": ctx.guild.id, "afk_members": []}
await collection.insert_one(post)
data = await collection.find_one({"_id": ctx.guild.id})["afk_members"]

    for i in data:
        if i["id"] != ctx.author.id:
            if status is None:
                status = "AFK"
            new_data = data.append({"id": ctx.author.id, "reason": status, "date": datetime.datetime.utcnow()})

            await collection.update_one({"_id": ctx.guild.id}, {"$set": {"afk_members": new_data}})
            await ctx.send(f"I have set your AFK: {status}")

@commands.Cog.listener()
async def on_message(self, message):
    if (await collection.count_documents({"_id": message.guild.id})) != 0:
        find_user = await collection.find_one({"_id": message.guild.id})["afk_members"]

        for i in find_user:
            if i["id"] == message.author.id:
                find_user.remove(i)
                await message.channel.send(f"Welcome back, {message.author.mention}! I have removed your AFK")
            else:
                for member in message.mentions:
                    for i in find_user:
                        if i["id"] == member.id:
                            await message.channel.send(f"{member.name} is AFK: {i['reason']}")
                        else:
                            return
grim vault
silent plaza
#
data = await collection.find_one({"_id": ctx.guild.id})["afk_members"]
```this is equivalent to ```py
future = collection.find_one({"_id": ctx.guild.id})
await future["afk_members"]
tranquil totem
#

what is future?

#

ohh nvm

silent plaza
#

something that will have a value in the future

tranquil totem
#

but why am i getting that error?

silent plaza
#

because you're subscripting a future

tranquil totem
#

subscripting a future?

silent plaza
#

x[...] is called subscripting

#

but it can also mean indexing, slicing, item access - whatever

tranquil totem
#

oh

silent plaza
#

solution here is to not dump everything in one line

#

because you've obviously being confused by what's being await'd/not

tranquil totem
#

so what changes are to be made in the command?

#
    @commands.command()
    async def afk(self, ctx, status = None):
        if (await collection.count_documents({"_id": ctx.guild.id})) == 0:
            post = {"_id": ctx.guild.id, "afk_members": []}
            await collection.insert_one(post)
        data = await collection.find_one({"_id": ctx.guild.id})["afk_members"]


        for i in data:
            if i["id"] != ctx.author.id:
                if status is None:
                    status = "AFK"
                new_data = data.append({"id": ctx.author.id, "reason": status, "date": datetime.datetime.utcnow()})

                await collection.update_one({"_id": ctx.guild.id}, {"$set": {"afk_members": new_data}})
                await ctx.send(f"I have set your AFK: {status}")
#

isnt this completely simplified tho

#

i cant find something simpler

#

?

tranquil totem
silent plaza
#

yup, perfect

tranquil totem
#

but would that make any difference?

#

what i did is actually more compact

silent plaza
#

yes, because you're awaiting the future, then grabbing the result

tranquil totem
#

awaiting the future?

#

whats future here?

silent plaza
#

the thing that find_one returns

#
future = collection.find_one({"_id": ctx.guild.id})
data = await future
data['afk_members']
tranquil totem
#

oh so would this work too```py
data = (await collection.find_one({"_id": ctx.guild.id}))["afk_members"]

#

added brackets

silent plaza
#

yup

tranquil totem
#

nice, thanks

#

but now this doesn't do anything at all```py
@commands.command()
async def afk(self, ctx, status = None):
if (await collection.count_documents({"_id": ctx.guild.id})) == 0:
post = {"_id": ctx.guild.id, "afk_members": []}
await collection.insert_one(post)
data = (await collection.find_one({"_id": ctx.guild.id}))["afk_members"]

    for i in data:
        if i["id"] != ctx.author.id:
            if status is None:
                status = "AFK"
            new_data = data.append({"id": ctx.author.id, "reason": status, "date": datetime.datetime.utcnow()})

            await collection.update_one({"_id": ctx.guild.id}, {"$set": {"afk_members": new_data}})
            await ctx.send(f"I have set your AFK: {status}")

@commands.Cog.listener()
# prefix = (await server_data.find_one({"_id": message.guild.id}))["prefix"].casefold()
async def on_message(self, message):
    if (await collection.count_documents({"_id": message.guild.id})) != 0:
        find_user = (await collection.find_one({"_id": message.guild.id}))["afk_members"]

        for i in find_user:
            if i["id"] == message.author.id:
                find_user.remove(i)
                await message.channel.send(f"Welcome back, {message.author.mention}! I have removed your AFK")
            else:
                for member in message.mentions:
                    for i in find_user:
                        if i["id"] == member.id:
                            await message.channel.send(f"{member.name} is AFK: {i['reason']}")
                        else:
                            return
#

the field in the database shows Array which i think is an empty list

#

the command isnt working :/

#

someone help me pls

tranquil totem
#

...

remote plinth
median swift
#

How could I get the total number of records in a table in asyncpg?

jaunty galleon
#

If that is what you mean ofc

median swift
#

so if for example, i stored the select in a variable named x, the len(x) would be the length?

jaunty galleon
#

Yes it should be.

woeful jolt
#

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 8 supplied.

#

error from

db = sqlite3.connect('poseidon_database_n001.db')
        cursor = db.cursor()
        sql = (f"UPDATE USER_DATA SET guild_name = ? WHERE guild_id = '{guild.id}'")
        val = (str(after))
        cursor.execute(sql, val)
        db.commit()
#

how can i fix it

grim vault
grim vault
mortal scarab
#

anyone using Pyside 6 currently, i have a bug thats pretty weird the DB work but doesnt complete transactions

mortal scarab
#

NVM thy caganged the function name

random copper
#

!python

#
INSERT INTO movie (title, director, stars, description, 3D, ChildrenAllowed, duration)
VALUES ("Frozen", "Chris Buck, Jennifer Lee", "Kristen Bell, Idina Menzel, Jonathan Groff",
        "When the newly crowned Queen Elsa accidentally uses her power to 
        turn things into ice to curse her home in infinite winter,
         her sister Anna teams up with a mountain man, his playful reindeer, 
        and a snowman to change the weather condition",
        0, 1, ""),

duration = TEXT but what would be the best way to put it in the values?

#

duration of the movie is 1h 42min

tawny sail
#

you can store the start and end timestamp of the movie

#

subtracting those 2 will give the duration

grim vault
#

Value in seconds or minutes?

gritty prism
#

Hey guys, why doesnt this work?py names=['confederations','athletics'] for ecos in names: sql = sql_con.execute(f"""SELECT [website] FROM [panorama].[dbo].[{ecos}]""") df = pd.DataFrame(sql, columns=['Website'])

#

trying to get a database from AWS using sql

#

dont even know if this is the correct channel though

random copper
grim vault
#

If you know it's in minutes you can easily convert for display and calculate with the value.

random copper
#

How ?

grim vault
#

Well, you could select all films by some specific conditions and sum the minutes to get the total length.

covert yarrow
#

Is there a need to create a ".db" file in MySql?

#

This would be my first project with mysql and I am confused because my program is connected to the localhost and not to a .db file together with my .py file.

random copper
gritty prism
#

thanks anyway lol

velvet edge
#

i cant connect admin password from database into html can u help me? i m using sqlite 3, pycharm, db base

random copper
#

how can i calculate the price in values its basically (9adults + 7kids) but it gives an error

#

idk if that's even possible in sql

#

any help is welcomed

grim vault
#

You can do basic math in sql (and more).

woeful jolt
#

sqlite3 database is locked

#

anyway to fix ?

#

db = sqlite3.connect('poseidon_database_n001.db', timeout=10)

#

but still locked

#

already did cursor.close()
and db.close()

proven arrow
#

@woeful jolt do you have any database browsers using it?

woeful jolt
#

yea

#

@proven arroweven i close it

proven arrow
#

Make sure to close it

woeful jolt
#

Thanks

#

thank you sir

torn sphinx
#

anyone knows things about python with MongoDB? I used localhost Database before now im trying to connect to a online Database with Atlas but everytime i try to connect it just tells me Auth Error I enterd password and user correctly like the exampleurl that where given: mongodb+srv://musicadmin:<password>@cluster0.xomx9.mongodb.net/test at the point where i used localhost the connectionstring looked like this: mongodb://127.0.0.1:27017 anyone knows a solution? Im not good in English and i just read the docs but that also not solved it....

plucky wave
#

how to define GuildDB

elder vessel
#

how can i use mongo DB atlas?

tawny sail
#

mongo db atlas gives you a database on the cloud, I think they give around 500mb for free, all you need is the url to connect to that database

#

and then it would be just like any other db running locally

elder vessel
tawny sail
#

have you created a cluster

elder vessel
#

ys

#

only first step completed

tawny sail
#

you should see a connect button in the clusters page

elder vessel
#

oh let me check

elder vessel
tawny sail
#

are you going to connect it via python code?

#

mongo db offers a GUI tool called compass which you can use for connecting as well

#

the mongo shell is a CLI tool for interacting with mongo db

elder vessel
#

what to choose from them

tawny sail
#

how do you plan on connecting? from python or would you like to use GUI tool

elder vessel
#

python

tawny sail
#

2nd option

elder vessel
#

ohk

tawny sail
#

and then select python instead of node

#

you will need to install a lib for connecting to mongodb, its called pymongo

tawny sail
#

if you check Include full driver code example, it uses pymongo

elder vessel
#

which version to choose of python?

tawny sail
#

3.6+

elder vessel
#

ohk

#

done

tawny sail
#

cool 🎉

acoustic wolf
#

Hello. I am in need of advice. What is the best practice for Python REST APIs for connecting to databases? Should I always use ORM? If I go without it, what is the standard way to template SQL statements? I'm new at building APIs. Eventually it will become an MLOps type of application - but that's in the future. What's best long term?

#

I'm still learning about ORM (SQLAlchemy) but the part where a Table object "reflects" the database tables kinda concerns me - how does it work under the hood? I'm sure it doesn't mean making a copy of the whole database at runtime but I wanna make sure.

torn sphinx
#
@client.command()
async def whois(ctx,member:discord.Member):
    db = sqlite3.connect('INTRO.db')
    c = db.cursor()
    c.execute(f"SELECT name , age , gender , location , hobbies FROM info WHERE memberid={member.id} and membername='{member.name}' ")
    result = c.fetchall()
    if result is not None:
        for row in result:
            Name = row[0]
            n=Name.title()
            Age = row[1]
            Gender = row[2]
            g=Gender.title()
            Location = row[3]
            l=Location.title()
            Hobbies = row[4]
            h=Hobbies[0].upper()
            mainh = h + Hobbies[1:len(Hobbies)]
            print(mainh)
            embed = discord.Embed(color=discord.Colour.red())
            embed.set_author(name=f'{member}', icon_url=member.avatar_url)
            embed.add_field(name='Name', value=n, inline=False)
            embed.add_field(name='Age', value=Age, inline=False)
            embed.add_field(name='Gender', value=g, inline=False)
            embed.add_field(name='Location', value=l, inline=False)
            embed.add_field(name='Hobbies', value=mainh, inline=False)
            embed.set_footer(text=f'Exposed by {ctx.author.name}', icon_url=ctx.author.avatar_url)
            embed.set_thumbnail(url=member.avatar_url)
            await ctx.channel.send(embed=embed)
            db.commit()
    else:
          print('bruh')
#

why isnt the else part working

#

dont mind the indentation in the above code.. i have it completly fine in my code

#

but the else part isnt workin

#

why is that

tawny sail
#

in sqlite3, the result var can never be None, it is either an empty list or populated list

#

try changing the if condition to if result:

torn sphinx
#

oh

tawny sail
#

in your case, an empty list is still not None, so the if statement always gives true

torn sphinx
#

ah i see

jaunty galleon
#

You should do:

if result:
    #the code
else:
    print('bruh')```
#

I think if statements is doing bool on the condition, and bool([]) returns False

#

!e

lst = []
if lst:
    print("It has data")
else:
    print("Doesn't have data")
print(bool(lst))```
delicate fieldBOT
#

@jaunty galleon :white_check_mark: Your eval job has completed with return code 0.

001 | Doesn't have data
002 | False
chilly nimbus
#

so if i host my database on elephant sql (a database as service provider) how do i even connect to it
i.e. a remote server

#

how do i connect to a remote sql server :,

jaunty galleon
#

You just put in create_pool dsn = URL from elephantsql server data

chilly nimbus
#

and user

jaunty galleon
#

I don't think you need it, only yhe dsn, min_size = 1, max_size = 3 I think

chilly nimbus
#

User & Default database : lznoopsnk
its showing me like this

#
    return fut.result()
asyncpg.exceptions.TooManyConnectionsError: too many connections for role "lznoopsnk"```
its showing me this, when i did

dsn = "the url"
user = "lznoopsnk"
database = "lznoopsnk"
password = password

chilly nimbus
#

guys a simple question

            CREATE TABLE userdemo(
                id = BIGINT PRIMARY KEY,
                balance = BIGINT,
                status = VARCHAR (128)
            )
        ''')

This code is giving me syntax error

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: PostgresSyntaxError: syntax error at or near "="
tawny sail
#

the = is not required

chilly nimbus
#

BRO WTF

#

I created a single table and a singe row in the table and it occupied 8mb

#

wtf is this

#

is heroku crazy

#

i am using heroku btw

#

bruh wtf happened there does anybody know

#

how can a table occupy 8mb with a single row

wanton lantern
#

hi is there any body know how to make donut pie chart 3d from inner in matplotlib python

grim vault
formal shell
#

I have this query:

SELECT * FROM members WHERE member_id=$1 AND guild_id=$2;

But I also need to fetch a position of this row with a couple things before. It should be ordered by one column and check where guild_id=$1.

strong robin
#

aight

#
   @commands.command(aliases=["toggle-welcome", "tog-welcome", "tog-welc", "toggle-welc"])
    @has_permissions(manage_messages=True)
    async def togglewelcome(self, ctx):

        db = sqlite3.connect('./dbs/welcome.sqlite')
        cursor = db.cursor()
        cursor.execute(f"SELECT toggle FROM main WHERE guild_id = {ctx.guild.id}")
        result = cursor.fetchone()
        if result is None:
            return await ctx.send("This guild has no welcome channel setup.")
        elif result == "on":
            sql = ("UPDATE main SET toggle = ? WHERE guild_id = ?")
            val = ("off", ctx.guild.id)
            tog = discord.Embed(title = f"![yes](https://cdn.discordapp.com/emojis/849069962014228490.webp?size=128 "yes") Welcome message disabled:", description=f"**{ctx.author}** toggled welcome message to off.", timestamp=datetime.datetime.utcnow(), color=discord.Color.green())
            tog.set_thumbnail(url = ctx.guild.icon_url)
            await ctx.send(embed=tog)

        elif result == "off":
            sql = ("UPDATE main SET toggle = ? WHERE guild_id = ?")
            val = ("on", ctx.guild.id)
            tog = discord.Embed(title = f"![yes](https://cdn.discordapp.com/emojis/849069962014228490.webp?size=128 "yes") Welcome message enabled:", description=f"**{ctx.author}** toggled welcome message to on.", timestamp=datetime.datetime.utcnow(), color=discord.Color.green())
            tog.set_thumbnail(url = ctx.guild.icon_url)
            await ctx.send(embed=tog)

        cursor.execute(sql, val)
        db.commit()
        cursor.close()
        db.close()``` im tryna make a welcome toggle for my bot
#

but i keep getting an error that 'sql' is referenced b4 assignment

#

@dark oxide

brave bridge
#

@strong robin If result is neither "on" nor "off" nor None, what should sql be?

strong robin
#

it should be none

#

ig

brave bridge
#

@strong robin No, variable that aren't given any value don't store None. They're just not defined, which is the issue you're having.

strong robin
#

but u cant do none if its trying to execute

#

yeah

brave bridge
#

Can you open the database in a DB viewer?

strong robin
#

yes

brave bridge
#

or do SELECT * FROM main

strong robin
#

thats my db

brave bridge
#

@strong robin And what type does the toggle column have?

strong robin
#

wdym

#

i inserted it as "on"

brave bridge
#

How did you create the table?

strong robin
#

i made it a text file

#

i think

#

*type

brave bridge
#

or right fetchone returns a tuple

strong robin
#

aight

brave bridge
#

Yeah, use named parameters

cursor.execute("SELECT toggle FROM main WHERE guild_id = :id", {"id": ctx.guild.id})

or ?-parameters.

strong robin
#

kk

#

but my error says sql is referenced b4 assignment

brave bridge
#

@strong robin Have you fixed the code? Do you understand what the issue was?

#

You could print out result after you fetch it to see what the issue is.

strong robin
#

it wasnt returning "on" or "off"

brave bridge
#

It's kind of silly because every database adapter supports different styles of parameters...

strong robin
#

aight

#

lemme try rq

#

('on',)

#

thats what it returnsa

brave bridge
#

right, and you're comparing it to "on". They aren't equal.

strong robin
#

mk

#

so should i just do 'on' or ('on',)

#

or should i slice it

brave bridge
#

You can compare result to ("on",)

strong robin
#

i tried but it didnt work

#

😦

#

ill try again though

#

if u want

brave bridge
#

Another powerful tool is setting the row type to Row: ```py
connection.row_factory = sqlite3.Row

it's a dict-like object that you can get values from by key. It's so much better than a tuple where you have to remember the order of values.
strong robin
#

yh

#

result[0]

#

returns on

tranquil totem
#

(mongodb)

runic saffron
#

Hey stupid question here,
i am trying to fetch some data from a heroku postgres database to a seperate machine(raspberry pi) through code? I can't find a tutorial or any information about how I would actually go about doing that. If anybody has a better idea of what I should do/search that would be great!
[Ping me so that I get a notification :)]

strong robin
#

uh

covert yarrow
#

Is there anyone here that already used MySQL as their database in Python TkInter? I have some questions.

strong robin
#

thx ily

dreamy cedar
#

hii

#

I have one question about Postgres.. When I do insert and if transaction violate the constraint still primary key is getting generated.... Is there any way to stop postgres from creating primary key? I only want primary key to be generated if transaction is fully committed.

snow widget
#

ok so i was setting up mysql and came accross a page https://prnt.sc/13o7yd7 i tried to reinstall but it still asks for some password....saw on youtube how to reset the root pass they said to make a text file in a disk and they had some password resetting command and saved it ....than they went to their mysql folder which had a bin file but my folder dosent...So now even after i uninstall all and try to start to set it up from start its not working....can someone help me with restting mysql?

Lightshot

Captured with Lightshot

dreamy cedar
snow widget
#

ok trying it now

little stirrup
#

Hey, so I've had this project on my server(running without fault) for about a month now, but suddenly when I ran it it gave me this error:

C:\inetpub\wwwroot\FinBot\Modules\Python>main.py
  File "C:\inetpub\wwwroot\FinBot\Modules\Python\main.py", line 35
    self.mongo: Union[MongoDB, None] = None
              ^
SyntaxError: invalid syntax```
This doesn't happen on my other development computer - where it runs fine, but errors  on my server and won't run. Can anyone give an explanation for this?
#

I was told to put it in here, though it is a syntax error so I assumed it was meant to be elsewhere.

grim vault
#

Downgraded python version which doesn't support type annotation?

little stirrup
grim vault
#

It was just a guess, hence the question mark. But it wouldn't hurt to check.

little stirrup
#

Ah, doing py -3.9 main.py worked, thanks.

snow widget
wet path
#

What is the default password for user postgres in postgresql

vernal glacier
# wet path What is the default password for user postgres in postgresql
Liquid Web

When connecting to PostgreSQL on Linux for the first time many admins have questions, especially if those admins are from the MySQL world. By default, when PostgreSQL is installed, a postgres user is also added. If you run the command: cat /etc/passwd … you’ll see the postgres user. postgres:x:26:26:PostgreSQL Server:/var/lib/pgsql:/bin/bash The...

wet path
#

Thanks buddy

#

But it is giving me error with psycopg2 adapter of postgresql

#

Password not provided

vernal glacier
#

you would normally use your postgres user to create your "personal" user (or an app-specific user) and use that one in your program

#

also, did you restart postgres?

wet path
#

What is role

#

Now, I am going to change the default password for postgres user.

#

It will be good if you guys share some material on how these database adapters works.

wet path
oak carbon
#

is there any schema limit on postgres?

#

if no is there an issue if i have like 5-10 schema

wet path
#

No limit

covert yarrow
#

Good day, is there a way to create a standalone MySQL database file instead of connecting to a localhost?

#

Because I am doubting if I can manage to package the app if the database file is not in the same directory together with my program files.

wet path
#

There is a concept of .sql file. You can import and export

#

You can use sqlite database if you want it this way

snow widget
proud berry
#

what is the best database to use for my bots?

brazen charm
#

postgres

thorn geode
#

or sqlite if it's small

brazen charm
#

pretty much

proud berry
#

i am making it to help me with my job
so its small ty

proud berry
#

error:
Traceback (most recent call last):
File "C:/Users/xxTox/OneDrive/Desktop/mini/Projeccts/Python/database.py", line 7, in <module>
con.execute('ID')
sqlite3.OperationalError: near "ID": syntax error

import sqlite3
con = sqlite3.connect('example.db')


con.execute('ID')
cur = con.cursor
cur.execute(5)
cur.execute(4)
cur.execute(3)
cur.execute(1)
con.commit()
for x in cur.execute('ID'):
    print(x)
con.close()
lusty inlet
proud berry
#

i did

#

but still hard for me

sonic hinge
#

why cant i use mongo db with web requests? its not working

dusk junco
#

How can I insert a value into only one column of a table instead of having to specify all of the columns?How can I insert a value into only one column of a table instead of having to specify all of the columns?

proven arrow
#

But for that to work your other columns must be nullable

dusk junco
#

Ok, I see

#

If not they would require a insertion or update

proven arrow
#

insert into table (column) values (?)

little quiver
#

Im working with some others on a messaging app and thinking of using SQL to store data. What would be best for this application. I have never used SQL before. From research, PostgreSQL looks good.

#

.@me if you respond plz

harsh pulsar
#

@little quiver sqlite is good for proof of concept and testing because you don't need to run a separate server

#

postgresql is a good default choice for most projects

little quiver
#

ok, ill go with that then

#

thanks

torn sphinx
#

hey what do attributes and constraints mean

#

in sql?

torn sphinx
#

how can I move my collections from one cluster to another in mongodb ?!

novel oak
#

Hi why when I try to update a value in my sqlite DB it returns this error

#

sqlite3.OperationalError: database or disk is full

#

but I have enough space

#

in the disk

lucid quartz
#

To migrate a SQLAlchemy database, we add an Alembic migration script for the intended migration, perform the migration, update the model definition and then start using the database under the migrated schema.

#

i am not sure if it will work

#

just try

lucid quartz
#

👍

dreamy cedar
#

Hii

#

I am using this query SELECT EXISTS(SELECT username,password FROM users WHERE username = %s AND password = %s); expecting postgre to return true or false but, it's returning ** none** ... How could I fix it?

fallow coral
#

im using sqlite3 for a discord bot database, and ive got the following;

c.execute(
  """UPDATE tasks SET ?=? WHERE space=? and name=?""", 
  ("name", new, space, name)
)

where c is my connection cursor. what i was expecting to happen was that SET ?=? would resolve to SET name=val_of_new, but instead i got
OperationalError: near "?": syntax error. anyone know how to resolve this/do the same thing a different way?

(ik that "name" is a string and i could therefore put it in the sql string, but its just in place of a dynamic value i havent set up yet)

#

the goal of this is to update a given value (currently "name", dynamic in future) for the rows that match the given values for space and name. however it seems that in ?=? the first ? is invalid. im pretty new to sql so im not sure how i might resolve this

proven arrow
#

@fallow coral Placeholders parameters (?) only work for values

#

Your using it for column names

#

It’s not possible to use it like that due to how the query is prepared and sent

fallow coral
#

ah okay, that makes sense

#

is there some way to do a placeholder for a col name? or should i do a few if statements with different executes

proven arrow
#

Why does column name need to vary?

fallow coral
#

its a discord bot command that takes the form $touch [name] [colname] [new_value], so the user can specify which value to change for the task

#

security is definitely an issue here, but its for a small group of us at work who trust one another

proven arrow
#

Well then you can build the query string depending on what input you receive from the command.

#

Or add validation to the user input so it only works with columns you have in the table

fallow coral
#

i will be doing validation, i plan to do it by flags like -name will change the name but -notexist will spit out the help embed for the command

fallow coral
proven arrow
#

That’s the same thing

#

I told you what you can do above. Use those ways if you need.

fallow coral
#

okay

novel oak
#

Hi why when I try to update a value in my sqlite DB it returns this error sqlite3.OperationalError: database or disk is full, but I have enough space in the disk, how can I solve this?

harsh pulsar
#

@novel oak are you sure you have enough space? is the sqlite database file on a different disk drive? it's also possible that the database file is corrupted.

faint blade
harsh pulsar
#

unfortunately you can't use query parameters for columns, table names, etc.

#

this is why you shouldn't use columns, table names, etc. that are generated from user input

lusty inlet
#

This can be done dynamically if you like by, e.g., querying your db to create a Python list valid_list of valid table/column names; then if userval in valid_list: ...

harsh pulsar
#

yeah, that's an option

inland wave
#

So a quick question:
I am trying to get the 2 rows seen in the SS printed, however when fetching the data, it returns nothing.

It can connect to the DB, and it is pulling for the right table.

harsh pulsar
#

what's dbc?

inland wave
#

cursor

harsh pulsar
#

it looks like you re-used a previous cursor instead of getting a new one

#

the old cursor won't be updated with the new query

#

don't reuse cursors.

inland wave
#

I did actually make a new one. TRhere is no reference to db/dbc outside of the func as that created thread errors

#

Full part

#

This is all contained in a function. In the mian code there is no reference to a db besides in functions which are not global vars

harsh pulsar
#

use dbc.execute then

#

db.execute returns a new cursor in sqlite3

inland wave
#

Ah that might explain it

harsh pulsar
#

i'd bet money on it

inland wave
#

How much a single little typo can break risitas

#

That did indeed fix it facepalm

#

Thanks for your help man Poggers

harsh pulsar
#

glad it's working

velvet edge
#

how can i connect password and database?

cerulean ledge
#
async def setprefix(guild_id, prefix):
    async with aiosqlite.connect("laborbot.db") as con:
        await con.execute(f"UPDATE guildinfo SET prefix=\"{prefix}\" WHERE guild_id={guild_id}")
        await con.commit()
        return 

Hi! So I use this for my discord.py bot to set the prefix for people who want a custom prefix, but it just doesn't work. No errors aswell. anyone knows why?

#

Ping me on reply please.

velvet edge
jaunty galleon
cerulean ledge
jaunty galleon
#

Ok, maybe try to do it with placeholders? And don't use f-string

cerulean ledge
velvet edge
#

bruh can u help me

velvet edge
runic saffron
regal relic
#

anyone here with Python experience who can help me out 😭 ? I got this beginner python/flask project due in 9 days, been stuck for 48 hours now trying to get this CRUD functionality to work (building a comment section), if I can't get it to work soon I'll never submit this project in time. 😓

covert nova
#

i want a tutorial on heroku

#

please anyone can explain me '

royal mesa
#

i'm making a dataset for my chatbot model soo to make it look natural i would want to have it a chat with someone anybody have some time to have a quick convo on my dms then i will convert the messages and use them for the model tia

proven arrow
torn sphinx
#

Guys what the most simple way to select all columns from two tables based on a common column name and then delete the entire data ? (in sql)

royal mesa
torn sphinx
#

Hello, anyone knows why i keep getting this error on my Windows RDP but on my Main PC its working?

pymongo.errors.ServerSelectionTimeoutError: cluster0-shard-00-00.onvi5.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1125),cluster0-shard-00-02.onvi5.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1125),cluster0-shard-00-01.onvi5.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1125), Timeout: 30s, Topology Description: <TopologyDescription id: 60b7b4c03f0c0024c3959266, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('cluster0-shard-00-00.onvi5.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0-shard-00-00.onvi5.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1125)')>, <ServerDescription ('cluster0-shard-00-01.onvi5.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0-shard-00-01.onvi5.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1125)')>, <ServerDescription ('cluster0-shard-00-02.onvi5.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('cluster0-shard-00-02.onvi5.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1125)')>]>
modest pulsar
#

hi, how can i get a column's name, when i have a loop that iterate the column's value on one row ?

slow grail
#
import sqlite3
con = sqlite3.connect(':memory:')
cur = con.cursor()

cur.execute('CREATE TABLE one (Title TEXT, Value TEXT)')
cur.execute('CREATE TABLE two (Title TEXT, Value TEXT)')
cur.execute('INSERT INTO one VALUES (?, ?)', ('Match', 'Match'))
cur.execute('INSERT INTO one VALUES (?, ?)', ('Match', 'Match'))
cur.execute('INSERT INTO one VALUES (?, ?)', ('Not Match', 'fpraoiwjotaijtoawa'))
cur.execute('INSERT INTO one VALUES (?, ?)', ('Not Match', 'waijrowaitjeituhseieyhsei'))
match = cur.execute('SELECT * FROM one INNER JOIN two ON one.Value = two.Value').fetchall()
not_match = cur.execute('SELECT * FROM one INNER JOIN two ON one.Value != two.Value').fetchall()

print(match)
print('\n')
print(not_match)```
#

I am trying to practice joins, in SQL,

#

However, this appears to keep bringing rows of all matching instead of non-matching as well

strong relic
slow grail
#

if i did inner joins

#

i get no info

#

just empty lists

strong relic
#

in that case there are no matches between one and two on the Value field

#

Maybe examine your dataset just in case? maybe something else is going on but doublecheck

proven arrow
#

Your not inserting any values into table two

strong relic
proven arrow
#

And if your learning try to pick better names for tables/columns.

#

Even people who use sql daily will be confused with the names you have picked in your example

hidden glade
#

cna nayone help me dbs? I need to create a databse per user signed up on my app

#

already have everything set just want help on making new db per user id

proven arrow
#

Why per user?

hidden glade
#

like per user who signs up

proven arrow
#

What database? What application is it?

hidden glade
#

it is a python password keeper/manager

jaunty galleon
#

Anyone uses PostgreSQL(elehpantsql) and has TooManyConnectionsError ?

proven arrow
#

Database is stored where?

hidden glade
#

so you'd login and store data for accounts

#

on db file sqlite

jaunty galleon
proven arrow
hidden glade
#

i have a login and register db set up where user cna login etc

proven arrow
#

Storing centrally or on users device?

hidden glade
#

plus a database to store data but its the same for every user

jaunty galleon
hidden glade
#

i want to make it on a server this is a class assignment and what im doing could potentially give me a 100

#

okay boss

jaunty galleon
#

And than:

async with self.bot.pool.acquire() as conn:
  #somrthing with the db```
And that's it(every message it opens it like that if it matters
harsh pulsar
proven arrow
#

But since it’s an assignment you can probably get away with it

jaunty galleon
#

Why does that matter?

#

Someone told me to do it I don't know what it is

harsh pulsar
#

i expect that acquire should block until there are free connections in the pool

proven arrow
#

Just leave it out, so it can use the default which I’m not sure what it is. Or you can increase the default number to match your installation.

jaunty galleon
#

So I can remove it?

#

And it should work?

proven arrow
#

Yes

jaunty galleon
#

Thank you very much!

hidden glade
#

this is so confusing LOL

modest pulsar
modest pulsar
#

Do you know how to delete one record with sqlite3 ? Not an entire row, but just a value

#

I used DELETE but i don't know how to use it specifying a column too

proven arrow
#

DELETE is for deleting row(s).

#

For a single column of a row, you can set it to null by using UPDATE statement.

modest pulsar
proven arrow
#
create table t1 (id int, val text);

insert into t1 (id, val) values (1, 'data');

update t1 set val = null where id = 1;