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()
#databases
1 messages · Page 152 of 1
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**
For execute_batch the values need to be a list iterables.
From the error its seems you are only supplying a single list.
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
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
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)
);
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
Your pipeline table id doesnt have a unique constraint.
You can set it as primary key
@proven arrow
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
thank you so much @proven arrow , I will try it bro
its a currency system and its a public bot
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.
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
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!")
Thank you so much bro for saving me, it worked 😋
someone knows if it's possible to make flask-migrate detect secondary tables declared with "db.Table" ?
Can someone point me in the right direction when it comes to proper project organizing for SQLAlchemy?
How do I do that!?! I barely know any SQL so 🙂
CREATE INDEX some_name ON some_table(columns...)
How do I use it though? No idea what indexes are.
(Just need a basic thing, I can figure out the rest myself)
indexes are for decreasing query times.
they can dramatically increase performance by avoiding sequential scans on the tables.
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;
??
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
great, i just accidentally dropped all tables on a database at work.. and don't have permission to restore the backup.
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?
that's... awful. why do you have the ability to drop tables?
So sorry to hear that. Hope everything can be rectified.
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
yeah, seems like a good time to double check your permissions
flask shouldn't have any database access at all.. sqlalchemy?
yes
just a stupid mistake, but it could cost a few hours of work depending on how fast it's restored...
@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;
An online SQL database playground for testing, debugging and sharing SQL snippets.
there might be a better way to get the distinct channel id here
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.
what do you mean by this?
select for all channel ids.
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
so you want to do the entire thing in postgres and not in python?
Ideally. If the query would get ugly then I could use python
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
An online SQL database playground for testing, debugging and sharing SQL snippets.
ah not quite
An online SQL database playground for testing, debugging and sharing SQL snippets.
-- 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
Oh awesome! Thanks!
wow thank you so much salt that works like magic. Really appreciate your time.
Do we really need to use psycopg2 with SQLAlchemy?
It looks like I was able to do CRUD without using psycopg2
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)
How do you see if a collection exists in database in pymongo?
@quick bloom could you help me with the database part pls?
use db.list_collection_names with a filter that will match for the specified collection name
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
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
Lot of error 
@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')
Ok
No
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
;
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)
just make perm_blacklist.json and when you load the cog
make 2 jsons
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.
use ctx.user.id
Hello
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
edit: I just saw that"perma_blacklisted": []means it's a list, butperm_blacklist[str(user.id)] = useris for dictionaries. This should fail with an error.perm_blacklistis a dictionary, sorry about that.- You use different filenames for reading and writing and you write inside the read (the with statements should have the same indent).
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?
You need to use a MongoClient object
Because each row is represented as a tuple.
And so you getting a tuple back
SELECT productID
FROM Products
WHERE Products like 'chee[s,z]e';```
is this correct?
if i want to find cheese/ cheeze
i am getting pymongo.errors.ServerSelectionTimeoutError while trying to connect mongoDb to my poython code. can anyone please help?
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
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Which database?
SQL query to retrieve the productID of products which have a productName that contains the word cheese (or cheeze).
using regex
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
how to check if a field exists in a document in mongodb?
how to be specific to a single document not whole collection while using it?
🤔
you could add some more info to the query that would be specific to that document?
collection.findOne({_id: <doc id>, field: {$exists: 1}}
collection.find({"_id": 0,'date':{"$exists": False}})
yeah
I'm using this it's not giving me anything
wdym?
even if a date exists
what does it return?
<class 'pymongo.cursor.Cursor'>
yes find returns a Cursor
you're supposed to iterate over it to see the documents it returned
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
- if doesn't exist create a new one
- else check the date with some value and makes changes
@burnt turret
srry for pinging lol
why are you using find here instead of find_one?
oh that can be fixed I was trying everything and send the one with find lol
yes the list empty so i can use it as a falsy value
I just found the solution as i was chatting with u lol
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
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
yes upsert wont do here
nvm i don't know of a way to do that in a single query, sorry 
so gotta do with the traditional python then
there might be some way that i don't know of, but the easiest would be just using python here i guess
oh ok thanks dude
i made a file that write the database program again (rewrite) incase someone somewhy edit the file
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.
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
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
ok so (1) learn about creating safe queries https://realpython.com/prevent-python-sql-injection/ -- even when you're just working on your own thing, it's good practices to not drop arbitrary strings into queries
(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
alr, thx man
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))
What is the best way to check if a table exists using Python/SQL query?
using PostgreSQL
!with
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.
also you don't need .readlines to iterate over a file - in fact you probably shouldn't do this
.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
oh
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))
so its faster that way?
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
👍
do you want to extract the 100 lines afterwards?
you can do it in a single pass over the file
yeah thats exactly what I need to do afterwards
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
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)
btw neither of these are "database" questions
im getting for i in loaded["entrys"]: KeyError: 'entrys'
these really both should be in help channels (see #❓|how-to-get-help )
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
From the information schema
It should have a table called tables.
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?
@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
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
ok, do you understand the problem with str(allusers)?
kind of.
!e ```python
allusers = [1234, 5678, 9876]
print(repr(str(allusers)))
@harsh pulsar :white_check_mark: Your eval job has completed with return code 0.
'[1234, 5678, 9876]'
str(allusers) returns a single string '[1234, 5678, 9876]'
this is almost certainly not what you want
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
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
but why does it show the print thats in that if statement?
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]')
@harsh pulsar :white_check_mark: Your eval job has completed with return code 0.
True
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
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?
Parameters should be provided as an iterable like a list, tuple, dict
You might want to line.strip() because this method will include the line ending (or add a \n to the comparison which I would not recommend). Maybe even line.startswith("POSITION ") would be enough.
yep, that's important
@balmy aspen i got it working with regex, not pretty but effective https://regex101.com/r/QPAgsH/2/
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/
U pinged the wrong person i think
nope, i pinged you. you had suggested using regex for a problem that "Supreme Patriarch" was working on
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
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
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?
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
im not sure there needs to be a big difference in terms of the implications for the user
Hey guys, does anyone know about any python's packages for rain data and forecasting?
https://openweathermap.org/api use this api alongside the request module
Simple and fast and free weather API from OpenWeatherMap you have access to current weather data, hourly, 5- and 16-day forecasts. Historical weather data for 40 years back for any coordinate. Weather maps, UV Index, air pollution
and historical data
thanks!
how to whitelist my heroku application ip in mongodb atlas?
how do i edit a database using python
sql databse
How to create a database and learn these codes like SELECT, CREATE, etc?
xD
https://thepygrammer.blogspot.com/2020/11/login-system-1-database-creation.html
A login system program using MySQL connection with Python.
does heroku give you static external IPs? i don't believe so
Yah it doesn't
Gotta add some extra adons to make it satic or something
Whitelisted every IP for now 😥
This the only way right?
dunno, haven't tried it
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
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
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)
im just wondering on how that thing where you send a snap and it stay still in your phone until you're connected and so much more stuff i like when it comes to how snapchat deals with data
What’s wrong with MySQL encoding?
There is not way of knowing for sure what they do it like without seeing their code or architecture
Some ways they can do this is by using local storage or local device db
How do I make a list in a SQlite DB?
Nothing is wrong if you use the correct encoding type.
the issue is that its not UTF-8 by default 😔
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
🤔 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 
!d contextlib.closing
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()
```...
Doesn't sqlite alread support context manager, why make your own?
The question is if you need to open/close the connection all the time.
oh ok
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.
theres gonna be long periods (possibly days) where no commands will be sent, id rather shut the connection off if its idle for so long. im not really expecting more than ten commands a day either
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.
Define how simple? How do you intend to use it or write your code for it. CMS can be quite complex, not only the database but also how you write the server side code.
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.
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
Yes
That could be achieved with something like this
No
👍 _ _
u mean ye?
Yes you can set x = x+1
thanks.
@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.
is there a wildcard for WHERE? i know its kinda redundant but i have a use for it
@fallow coral what do you have in mind? hypothetically even
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
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
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
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')```
oh, don't use f-strings for this. use parameters
I can't?
@grim vault i was replying to the other user
you're doing it correctly
wcj is not
do f-strings misbehave? or is it a best practice thing
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)
@harsh pulsar :white_check_mark: Your eval job has completed with return code 0.
qmark
okay, ill use params if fstrings are an issue
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
okay, cool
is there some value i can give to newArg that means "literally any value is accepted for this column"?
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))
okay, i'll do it like that if theres no other way
Or use keyword argument packing.
the ? thing works in INSERT INTO table VALUES (?, ? ,?), right?
yes
okay, thanks for your help guys!
!e
!e
import glob
for file in glob.glob("*"):
print(file)
!e
import glob
for file in glob.glob("/config"):
print(file)
@nova dawn :warning: Your eval job has completed with return code 0.
[No output]
!e
import glob
for file in glob.glob("*"):
print(file)
@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
how do you create a new field in an existing document using pymongo?
honestly idk lol
i usually use sql
!e
import os
print(os.cwd())
!e
import os
os.system("ls -l -a")
@nova dawn :warning: Your eval job has completed with return code 0.
[No output]
use update_one, e.g. .update_one({'_id': '1234'}, {'$set': {'x': 'hello'}}) sets the x field to 'hello' in the first document with _id of '1234'
but would this also preserve the other fields? i.e. if i had a field called y would that still be there if i use this method?
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)
what OS are you using
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
so does it work for you now?
Yes please
Thats great
I believe so, but check the mongo docs for updateOne to confirm
okay thanks
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
bro check out this crazy exploit https://www.youtube.com/watch?v=-B_qto2a4ls
check your listFertCombTwo again. it probably contains only one argument.
https://www.psycopg.org/docs/extras.html#psycopg2.extras.execute_values
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.
How to fix MySQL connector connection refused
Hi, is there anyone have a resource or can explain what is sql GROUPING() function ? ?
@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
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()
??
How can I store data for an afk command?
I wanna connect discord.py to mongodb(PyMongo)! Where do I start from?
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
Can you use ORDER BY user.xp DESC LIMIT 20?
You don't "connect" them as such, you just create a pymongo client and use it
But where do i start from?? Any doc? Any examples of mongoDB with Discord.py!! I am confused in that!
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
I don't think you can find anything specific on discord.py + mongoDB, but you shouldn't need it either I think
as long as you know how they work individually
Actually I am new to databases!!
depends on what youre doing
that's like asking "is it better to use a spoon or a fork"
lmao
ah help plis?
is this even readable? sorry if it isnt lol
I wanna do a wed application relate to discord
web*
yeah, well, just focus on learning mongoDB
However I'd recommend you use shelve
hmm
man do you know why it doesnt store xyz' in the db?
i sent the code above
This isn't a database question--be sure to read the channel topics. But yeah it depends on what you want to do.
i mean if i try storing any string with a ' .. it doesnt store it
well, you're using those ' to show where the strings start and end
so it probably clashes with that
😥
so how do i fix it lol
i thought those were meant to store string valued variables in the db lol
wdym?
ah i mean like
nvm i was wrong
ye ye im doin it
You def don't wanna use c++ for that
the c++ bot lib is not fun
ah its still not working ;-;
it still doesnt store xy'
did you escape it with two slashes?
yesss i did
idk
maybe this is worth a read
okay, well that solves you issue?
look at the last embed.. and the name field
ah no it doesnt save xyz'
it does?
yes only if i input the value as xyz''
yeah, then just input that
ahh lemme look into it again lol
ah damn it works.. tysm : D
ah but i still actually didnt get the logic.. what does escaping a character mean
if u can .. explain with an example : D
shelve? is it free??
like this??
import dsicord
imagine I wanna print the text
My name is "vim vim", what's yours
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
@west furnaceBut is it helpful in discord.py
so you need to force it to see it as part of the text, by "escaping" it
like this
print("My name is \" vim vim \", what's yours"))
yes ofc
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?
if you need a database
@novel oak if you want people with > XP first you should use DESC
ok
shelve will work as a database!! right??
ohhhhhhhhhhhhhhhhhhhhhhh
i see yes!!!!!!
the single quote was clashing with the single quote i input into the value
i see
If I would get some examples how it works in discord.py, that would be really helpful!!
u learn something new everyday
exactly
why do you need a database?
To store values!! like changing the server_prefix! and more!
lel yes ofc... i ws not having issues with dpy part.. i just had the issue with the db part lol
Do you know Any Examples online?? to understand better
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
hmm? what examples?
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
you need to look at examples for the shelve module
leave your bot project to the side for a while
and start a new one, where you play around with shelve
Ok!! So that will make me understand how shelve works!! You mean to say that, Right?
I came across DiscordDBPlus, Do you know something about it?
yup, exactly
I would advise against it, unless you have a specific reason you want to
use a channel to store data
yeah no, that's a bad idea
Okay! Lets try shelve!

good luck
this is the one! right??
Thanks a Lot 👍
yup. you might be able to find some tutorials online as well
Yup!! Thanks alot for your help Bro!!
np
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()
Hmm interesting
I see
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?
What do you use for databases when you programm .py
I use .json
When I populate the database I did
python manage.py loaddata datadump.json
Anyone knows how to fix PostgreSQL(asyncpg(elephantsql)) TooManyConnectionsError error?
JSON isn't a database
Most people tend to use SQL based databases
json is not database!
JSON is a data format
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)
anyone here work with discord.py?
But you can save all thinks that you have to save after a command
What's a good online source to start learning SQL?
@opal hill Try sqlbolt.com
Thanks! I'll check it out
How do I start learning?
Start reading?
Can we call the shelve module is somewhat same as Json??
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
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
A ? is only good for one value. You can't use a list. You'll need to do it per entry or make as much ? as entries.
cur.execute(f'UPDATE Drugs SET rejected=1 WHERE id IN ({",".join("?"*len(rejected))})', rejected)
# or
for rej_id in rejected:
cur.execute('UPDATE Drugs SET rejected=1 WHERE id = ?', (rej_id, ))
why am i getting this error?
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"]
something that will have a value in the future
but why am i getting that error?
because you're subscripting a future
subscripting a future?
x[...] is called subscripting
but it can also mean indexing, slicing, item access - whatever
oh
solution here is to not dump everything in one line
because you've obviously being confused by what's being await'd/not
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
?
see if you can fix this
so ```py
data = await collection.find_one({"_id": ctx.guild.id})["afk_members"]
```py
data = await collection.find_one({"_id": ctx.guild.id})
collection = data["afk_members"]
yup, perfect
yes, because you're awaiting the future, then grabbing the result
the thing that find_one returns
future = collection.find_one({"_id": ctx.guild.id})
data = await future
data['afk_members']
oh so would this work too```py
data = (await collection.find_one({"_id": ctx.guild.id}))["afk_members"]
added brackets
yup
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
...
its still not a database
How could I get the total number of records in a table in asyncpg?
SELECT * FROM table should return a list of asyncpg.Record objects(each object per row of data). If there are two rows, the len() on the list would be 2, and so on
If that is what you mean ofc
so if for example, i stored the select in a variable named x, the len(x) would be the length?
Yes it should be.
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
SELECT COUNT(*) FROM table will also do the job.
Is after some sort of list? Also use a ? for the guild_id:
db = sqlite3.connect('poseidon_database_n001.db')
cursor = db.cursor()
sql = "UPDATE USER_DATA SET guild_name = ? WHERE guild_id = ?"
val = (str(after), guild.id)
cursor.execute(sql, val)
db.commit()```
`val` must be an iterable object.
anyone using Pyside 6 currently, i have a bug thats pretty weird the DB work but doesnt complete transactions
NVM thy caganged the function name
!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
you can store the start and end timestamp of the movie
subtracting those 2 will give the duration
Value in seconds or minutes?
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
minutes i think its good if i put 102 in it like in minutes?
If you know it's in minutes you can easily convert for display and calculate with the value.
How ?
Well, you could select all films by some specific conditions and sum the minutes to get the total length.
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.
too many string quotes? try 1 "
Naw it wasnt that, my dumbass friends screwed with the column names
thanks anyway lol
i cant connect admin password from database into html can u help me? i m using sqlite 3, pycharm, db base
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
You can do basic math in sql (and more).
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()
@woeful jolt do you have any database browsers using it?
Make sure to close it
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....
how to define GuildDB
how can i use mongo DB atlas?
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
what URL
?
how to get the url to connect to that database
have you created a cluster
you should see a connect button in the clusters page
oh let me check
its saying choose a connection method wht should i choose
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
how do you plan on connecting? from python or would you like to use GUI tool
python
2nd option
ohk
and then select python instead of node
you will need to install a lib for connecting to mongodb, its called pymongo
done
if you check Include full driver code example, it uses pymongo
which version to choose of python?
3.6+
cool 🎉
yea i saw that
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.
@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
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:
oh
in your case, an empty list is still not None, so the if statement always gives true
ah i see
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))```
@jaunty galleon :white_check_mark: Your eval job has completed with return code 0.
001 | Doesn't have data
002 | False
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 :,
You just put in create_pool dsn = URL from elephantsql server data
what about host, port etc
and user
I don't think you need it, only yhe dsn, min_size = 1, max_size = 3 I think
also, in elephant sql its showing me user and database both in the same tab, does this mean both have the same thing?
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
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 "="
the = is not required
Yeah it's ok
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
hi is there any body know how to make donut pie chart 3d from inner in matplotlib python
please use binding variables (I wonder how often you were allready told that):
c.execute("SELECT name, age, gender, location, hobbies FROM info WHERE memberid=? AND membername=?", (member.id, member.name))```
Someday I'll come to your server and name myself `'; DROP TABLE info; --`
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.
lol.. sure
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" 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" 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
@strong robin If result is neither "on" nor "off" nor None, what should sql be?
@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.
Can you open the database in a DB viewer?
yes
or do SELECT * FROM main
@strong robin And what type does the toggle column have?
How did you create the table?
or right fetchone returns a tuple
aight
Yeah, use named parameters
cursor.execute("SELECT toggle FROM main WHERE guild_id = :id", {"id": ctx.guild.id})
or ?-parameters.
@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.
it wasnt returning "on" or "off"
ok
It's kind of silly because every database adapter supports different styles of parameters...
right, and you're comparing it to "on". They aren't equal.
You can compare result to ("on",)
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.
what does { multi: true } do in https://docs.mongodb.com/manual/reference/operator/update/pull/
(mongodb)
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 :)]
uh
Is there anyone here that already used MySQL as their database in Python TkInter? I have some questions.
thx ily
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.
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?
I would suggest to delete the mysql file from C:\Program Files\ and then try to reinstalling it
ok trying it now
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.
Downgraded python version which doesn't support type annotation?
It worked yesterday though, and I didn't change anything
It was just a guess, hence the question mark. But it wouldn't hurt to check.
I didn't mean to come off as aggressive if I did, but I will check.
Ah, doing py -3.9 main.py worked, thanks.
ok when i reinstall https://prnt.sc/13oboy8 maybe this has to do any guidence?
What is the default password for user postgres in postgresql
there is none 🙂
see: https://www.liquidweb.com/kb/what-is-the-default-password-for-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...
Thanks buddy
But it is giving me error with psycopg2 adapter of postgresql
Password not provided
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?
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.
Is the role pointing me to access control things
is there any schema limit on postgres?
if no is there an issue if i have like 5-10 schema
No limit
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.
There is a concept of .sql file. You can import and export
You can use sqlite database if you want it this way
Guys if anyone knows why this error and what to do https://prnt.sc/13olyq2
what is the best database to use for my bots?
postgres
or sqlite if it's small
pretty much
i am making it to help me with my job
so its small ty
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()
See some demos: https://docs.python.org/3/library/sqlite3.html
why cant i use mongo db with web requests? its not working
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?
Just specify one column.
But for that to work your other columns must be nullable
insert into table (column) values (?)
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
@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
how can I move my collections from one cluster to another in mongodb ?!
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
SQL constraints are used to specify rules for the data in a table.
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
gotchu
👍
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?
problm is sorted out
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
@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
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
Why does column name need to vary?
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
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
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
ive been warned against putting fstrings directly in the execute(), should i do query = f"..." then pass execute(query)? or would that still be "bad"
That’s the same thing
I told you what you can do above. Use those ways if you need.
okay
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?
@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.
apparently if you are backing up or cloning your sqlite database, and you run the backup during an insert or other write operation, the backup could be corrupted https://stackoverflow.com/q/5274202/2954547
Yeah that's the same thing, it is okay if you validate the input though. For example you can have a list of all columns one can specify, then try to see if the user's value is in that list. If it is then continue and do the query, if not that is dangerous and you should return.
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
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: ...
yeah, that's an option
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.
what's dbc?
cursor
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.
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
Ah that might explain it
i'd bet money on it
How much a single little typo can break 
That did indeed fix it 
Thanks for your help man 
glad it's working
how can i connect password and database?
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.
plz help me
Well, as far as I know, if it's a command, a command takes in a ctx argument. No event with these parameters as well
no its a function i use in a command
Ok, maybe try to do it with placeholders? And don't use f-string
I mean f strings work whereever else in my code sqlite related
bruh can u help me
wth this
Anybody know of a tutorial/better docs for how I would do this?https://devcenter.heroku.com/articles/connecting-to-heroku-postgres-databases-from-outside-of-heroku The steps on the documentation don't actually explain how to do it.
ok could be that thx
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. 😓
You should ask in #web-development for flask questions
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
You’ll get better datasets online
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)
no there are no datasets online that arent randomly scraped from reddit or any other website that do not contain sexual harassments or racial harasment
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)')>]>
hi, how can i get a column's name, when i have a loop that iterate the column's value on one row ?
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
LEFT JOIN returns records from the left table (one) and the corresponding matching records on the right (two), so if some records from two have no matches, then they shouldn't be displayed
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
Your not inserting any values into table two
lol I was under the impression that the values were already inserted beforehand
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
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
Why per user?
like per user who signs up
What database? What application is it?
it is a python password keeper/manager
Anyone uses PostgreSQL(elehpantsql) and has TooManyConnectionsError ?
Database is stored where?
Use a users table
Generally connection pool would solve it. Clearly your opening more connections than your setup allows
i have a login and register db set up where user cna login etc
Storing centrally or on users device?
plus a database to store data but its the same for every user
I use:
bot.pool = bot.loop.run_until_complete(asyncpg.create_pool(dsn = URL, min_size=1, max_size=3))
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
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
usually in python, a database cursor has a description attribute that contains info about each column, including the name
https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.description
https://www.python.org/dev/peps/pep-0249/#description
Generally bad idea to keep a table per user. See here for some reasons. #databases message
As for password managers I don’t have much knowledge for that domain so you might want to do some research for how others do it.
But since it’s an assignment you can probably get away with it
Max size 3?
i expect that acquire should block until there are free connections in the pool
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.
Yes
Thank you very much!
this is so confusing LOL
don't worry, i found a way to do it, but thx for your help !
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
DELETE is for deleting row(s).
For a single column of a row, you can set it to null by using UPDATE statement.
oh, i can just equal it to NULL ?
create table t1 (id int, val text);
insert into t1 (id, val) values (1, 'data');
update t1 set val = null where id = 1;
