#databases
1 messages · Page 135 of 1
yes, strings take more space
you can index string columns
but indexing integers is faster
there's also a more conceptual thing
you can look up natural vs surrogate keys
which, again, is part of the relational model of data
knowing the theory is quite helpful IMO
It's not my project, and the owner makes a big thing out of performance
🥴
this is a bigger reason
not to have clan tag as the PK
When I query my MongoDB Atlas db using pymongo
import pymongo
cluster = pymongo.MongoClient('mongodb+srv://Yash:<password>@cluster0.pfcfw.mongodb.net/<dbname>?retryWrites=true&w=majority')
db = cluster['dbname']
coll = db['drinks']
coll.find()
It's return back a cursor object and not the documents in my collection. :-
<pymongo.cursor.Cursor at 0x13d47bc5a60>
What's the problem here? I don't even know what a cursor object is, I'm just getting started with MongoDB
I want to make a message track level up bot, i need database right? Is it SQL? If it is, what is the best place for learning it for the level up system?
The cursor object is iterable and contains all the documents which matched your query, you can loop over it with a for loop:
for document in coll.find():
Has anybody tried async support of sqlalchemy 1.4 (beta)?
I would try fastapi on a new project, but:
In the fastapi's documentation "databases" + "sqlalchemy" is the suggested combo,
But sqlalchemy's own asnyc api solution is under development.
So which solution would be better?
databases + sqlalchemy VS sqlalchemy 1.4 (beta)?
https://fastapi.tiangolo.com/advanced/async-sql-databases/
https://docs.sqlalchemy.org/en/14/orm/extensions/asyncio.html
FastAPI framework, high performance, easy to learn, fast to code, ready for production
Make sure folder is not containing any spaces in the filename
Roght the folder --> clik rename
Remove all the text, type in sqlite
Hit the enter key.
Now open cmd, type in cd c:\sqlite and hit the enter key.
Actually wait, ur issue is a ACL issue.
No spaces in file name
what is it?
And where's that
If you still get access denied, you can fix the permsssions manually or download sqlite from their website again
What is the extension of the file?
Is it a zip file?
You can download a portable version (zip) and executable installer
I downloaded the first one
Probably you need this:
SQLiteStudio-3.2.1.zip
or this:
InstallSQLiteStudio-3.2.1.exe
zip -> You don't need to install it on your machine. Just extract it and run the exe...
I never used this tool... 🙂
Oh
So i downloaded the zip
what should i do next? move it to the sqlite folder?
Try to extract the content of the zip and run the exe file.
This article explains how to zip and unzip files.
Check the "To unzip files" section
nvm it is too hard this database
Hey guys, lets say I have 3 tables A B C in database. Each entry in B can have multiple Entries in C. How can A have B and C foreign keys and ensure that C is an option for that B entry
A B C x has a or b as options , y has c as an option.
1 x a
x y b
a c
If A had x and c for example it should error or something
like how do I set up the relationships and constraints, or if there is a better way to set up the tables in the first place
hehe
sec I'll give an example
A = Accounts
B = Account_Type
C = DiscountOptions or something
account types lets say can be Business or Individual
Businesses can have a discount of Null, Dealer, Super Dealer
Individuals can have a discount of Null, Loyalty1, Loyalty2 or whatever they are called
How would you set the tables up for such a requirement
@torn sphinx How many discount types can an account have?
Uhmmm, I don't know a handful I guess
Then you can have something like this:
accounts
- id
- account_type (FK to account_types table)
account_types
- id
- type
account_discounts
- id
- account_id (FK to accounts table)
- discount_id (FK to discounts table)
unique constraint on both (account_id, discount_id)
discounts
- id
- name
hmm so basically a many to many relationship between accounts and discounts. but that doesn't ensure that a discount belongs to that account type
@proven arrow
Why am I getting this error:
syntax error at or near "$1"
The code that the error is coming from is this:
await self.client.db.execute("UPDATE users SET ($1) = ($1) + ($2) WHERE userid = ($3)", item, amount, ctx.author.id)
You cant use parameters for column names
You can't
I am creating a column for each item, and I am using the item variable as the item
One thing you can do is create a trigger
What do you mean you can’t?
I meant:
You can't?
Yeah not possible with parameterised queries as the query is sent separately from the values to the database
What could I use instead, because one column for each item would be too long
And would extend past the bigint range
I don’t understand clearly what you mean
So I am making a column for the items a playing has
A column for each item?
Ya
That’s not a really good idea.
Then what should I do?
It would be better to have an items table where you store all the items. In this table you just need 2 columns (minimum), id and item name.
Then another table that sits in the middle where you store each item a user has. The table in the middle will have 2 columns minimum, (user_id, item_id) where they both are foreign keys to the user and items table.
Does that make sense or did I lose you? 😆
You can have 2 columns in a column?
No, 2 columns in the table.
Wait so a table just for items
That’s the minimum you need for it to work like that. Obviously you can store more for extra data.
Yes, that way you can dynamically add new items/remove
So what I said previously with the creating extra tables is a many to many relationship (you can look it up) but that is what you need. This is because a user can have many items, and each item can belong to many users.
Well I have a table just for their userid, balance and items
Where’s your users table?
Could I add a dict to it like this?
{itemid: 1, amount: 1}
Sure you can, but it might also mean you have more processing to do. And you data would better fit and easier to manage when it is separated into tables/columns like I said.
Hi. Would anyone be able to explain to me how sqlite3 transactions work. The docs are a little confusing and contradictory to what I thought.
Does anyone also know of any good (async) sqlite3 libs/wrappers? aiosqlite also doesn't seem to support controllable transactions and asqlite (a wrapper made by the d.py creator seems to be broken in new versions)
I understand sqlite is fairly fast so I am not dead set on the lib being async, however it would definitely be a plus
So like:
Column 1:
Food
Column 2:
Sword
uMongo again
new_submission = {
"code": in_map_code,
"creator": in_creator,
"map_name": new_map_name,
"desc": in_desc,
"posted_by": ctx.author.id,
"type": in_map_type
}
MapData(new_submission)
Last line produces an error: "TypeError: init() takes 1 positional argument but 2 were given"
This is the class:
@instance.register
class MapData(Document):
code = StringField(required=True, unique=True)
creator = StringField(required=True)
map_name = StringField(required=True)
posted_by = IntegerField(required=True)
type = StringField(required=True)
desc = StringField(required=True)
class Meta:
collection_name = "MapData"```
How am I giving MapData two arguments?? I am only using one dict.
I can't get a stack trace for some reason so I assume its the MapData class causing this. But could it be something else?
"TypeError: init() takes 1 positional argument but 2 were given"
keyword arguments are not positional arguments
and when you initialize a class it implicitly passes self along with other ags you pass in
How do I go about changing DBMS for my sqlalchemy application?
I feel like there should be an automated way to move data from one database to another, if they are supported by SQLAlchemy and I have the table definitions
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
If I'm trying to query a postgresql database with sqlalchemy, How do I find all rows of a number column that contains a number?
For example, lets say that I want to look for a number 266 and there are other numbers like 26 and 2666 and so I want all of them returned with it's closest match.
I have tried...
Locations.query.filter(Locations.site_id.like(266)
but it always appends the _1 after site_id Like so site_id_1?
[parameters: {'site_id_1': '266'}]
operator does not exist: integer ~~ unknown LINE 3: WHERE locations.site_id LIKE '266'
Your error is because your comparing an integer to string which Postgres doesn’t allow unlike some other databases. With pure Sql the way to fix this would be to cast your int column to text type.
So you should try an find a way to cast it with your orm .
Thanks, that helps a lot!
hi ^^
i'm using sqlite3, how do i check if data exists in the database and if not instert it? or i have to query in for every data?
hi
for a full discord message, what mysql data type should I use?
I think it only supports a maximum of 8mb.
json maybe?
It is for a tag command, I don't think it needs more than 2000 characters.
TINYTEXT – 255 Bytes (255 characters)
TEXT – 64KB (65,535 characters)
Hi, I'm wondering if it is okay to use variables for table names in SQL query. I've googled it up and some says using variables for SQL queries make it vulnerable to SQL injection and some says it's fine
which left me confused
you said for a "full discord message"
I thought you were talking about a Message object
@rain plank discord limits to 2000 characters per message, I would like to know a way to put a data type close to 2000 characters.
VARCHAR(2000)
thanks
Hey! I am trying to make a custom discord.py cooldown system through MySQL. I have 2 tables; cooldownTypes and cooldowns. cooldownTypes contains the name of the cooldown, the length it lasts, the number of times it can be used during that time period and the bucket effected. cooldowns contains a nullable user_id and server_id then a non-nullable name (reference to the cooldown type), expiry and usages. Each function in my Discord bot (commands or events) is given a list of cooldown types that effects it. I am using aiomysql.
So, what would be the preferred way of querying and updating the cooldowns table every time a command/event is issued? I can keep a copy of cooldownTypes in my code if needed as it won't be updated while the bot is online if this would be faster.
The best way I see would be to iterate through each cooldown that effects the current command, SELECT bucket,number FROM cooldownTypes WHERE name = %s and then, based on the result of that query (say it's member) do SELECT * FROM cooldowns WHERE user_id = %s AND server_id = %s AND name = %s AND expiry > now() AND usages > %s then, if anything is returned, display an error to the user, else test against the next cooldown. If no cooldowns are returned at all, I then have to iterate through them all again and SELECT usages FROM cooldowns WHERE user_id = %s AND server_id = %s AND name = %s and if one exists, I have to UPDATE to either add 1 to the usages or renew it. If one doesn't exist, I have to INSERT one. I feel like this is too many requests though; on a command with 3 cooldowns, I end up having to make 12 requests every time it is used successfully! Any ideas on how I can improve this?
Your well-written paragraph might be better for a help channel.
Alright I'll try
I'm curious, what are the custom bucket types you make? Discord.py provides built-in buckets that imo can meet almost every use-case imaginable
I’ve already asked a few times if some of the things I’m wanting are possible with discord.py’s implementation of it, and every time I’ve got something along the lines that it’ll be easier to just design my own version. But, my buckets are server, member and user which, yes, I believe discord.py provides all of (might not do user seperate to member, not sure)
Stuff like being able to not add to the cooldown if the command returns a sertain thing (for example, I’m wanting it so for my crime commands in my economy, one of my cooldowns is only added to if the crime is unsuccessful), having commands share cooldowns, being able to buy yourself out of a cooldown, cooldowns staying active after the bot restarting etc.
Except for the cooldowns staying active part, the rest can be easily achieved with the built-ins really
this is all stuff you'd have to add
How long is the cooldown?
Some of my cooldowns are to last multiple days
like check in the command body for the cooldown
Not adding the cooldown can be done with something like after_invoke/reset_cooldown
or in a cog_check if its all of the ones in the cog
But, say a cooldown allows a command to be used 3 times and it has been used 2 times, this would allow someone to intentionally get an error or want a failure as i would reset their cooldown to 0 instead of just staying as it is
true
There is a cooldown that effects all the commands in a cog, yes. I still don’t understand your point about using a database and not making them actual ‘cooldowns’. I thought a cooldown was just anything that stopped you from doing something more than x times in y time
if iwant to add a login system that remember all users and password would i need to use a database?
Yes
is it true that while scaling your foreign key is moved to a separate table and formed a relationship with the main table later on? On ORM based dbs
here i want to make a table out of visit_place by removing foreign key place_id, is this what scalling means or im doing wrong?
You don’t need to move the foreign key out to it’s own table. If you did then then there is no longer a foreign key and so then how would you define the relationship?
is this worthy?
Sure you can do something like that (pick what works best for your app), but what’s the purpose of the extra table. A user can visit many places?
yes
So then you don’t need the visits table. You can have a table for users, a table for places. And then have a junction table in the middle like the one your posted which has foreign keys for both.
The junction table is your pivot table, and you can store extra columns in that table if you like.
Three tables are fine, there’s no need for extra complexity.
a user has a option to visit place or just write review without associating the place and only add pictures
and i made separate table since it creates many null values when tried to accomplish within single table
can i dm just to clear my confusion?
What do you mean without “associating” the place?
If it helps
🙂
mad libs game == choices based game : rights ?
guyes how can i increment an integer value from a sqllite database
Well ye that eas the point that was why I was asking here lol. That’s why I was confused
.... This is not #discord-bots no wonder I confused you
for messages in all:
try:
if date != messages["date"]:
print(f" Today - {messages['time']}")
else:
print(f" {messages['date']} - {messages['time']} ")
print(f" From: ", messages['id'])
print(f" Message: ", messages['message'])
print("\n \n")
except:
print("something went wrong")
``` what is wrong with this message :\
nobody answered :\
Just be patient. If nobody answers, either nobody is currently online looking at this channel or they don't understand your question. Try clarifying. Saying things like What is wrong with this message :\ isn't very detailed
Its worked btw
Quick MySQL naming convention question, would it be reasonable to name my tables as 2021_week1, 2021_week2, etc...?
If not, any other suggestion?
hi, How do I change the hypesquad?
class discord.HypeSquadHouse
I dont know how to use it.
Time to learn how to work with databases now, anyone got any tips on how to get started?
I've created it, postgresql, but how to query
also trying to set up pgadmin4, if I can
i never touch postgresql with python or not with python
ah, why not?
i always use sqlite
😐
python3 + sqlite db
if you want to create db with sqlite use db browser for sqlite or the command line
i prefer db browser for sqlite
hm
may I ask why sqlite?
the ppl I'm working with have had postgresql experience but I'm curious to know why sqlite
it outputted as .db files
you can access the database with .db files
and to create the database itself is easier with db browser for sqlite
reading about it, it looks like you can create a database per user or stuff as well
yea
like, user who's accessing via an api
I'm learning a database for making an api
yes I know its going to be hard
good to know
yea inner join and join sucks especially if you have a lot of data
gotta normalize then denormalize it 😄
wdym?
database normalisation and database denormalisation
I was just talking about the overall thing is gonna be hard. Containers in docker on wine in linux with FastAPI and a database, either postgresql or sqlite.
…what that, and why did boss music just start playing?
google it
The process to alter the structure of a database is basically categorized into two ways one is Normalization and other is Denormalization.The following are the ...
oh geez sounds fun /s
depends
sqlite is also the best c project i have ever seen
you can
btw
you might need this
if you're using a raspberry pi for development, why do anything locally?
just set up an aws rds instance
ez
don't you have to provide some payment info before you can do that?
yes
actually, i forgot if small rds instances fall under free-tier
so it might not cost anything
(it probably doesn't)
but you still need a credit card
uh
what?
discord bot and learning?
sqlite + flask running in its own docker container
also a whole other thing I'm doing with someone else
there's probably a billion blog posts on this
i would skip the docker probably on the raspberry pi as you're resource-limited as it is
yeah
for now I'm just trying to learn databases
rest assured it won't be running on the pi
i suppose I could do sqlite locally and not on the pi.…
@jovial cedar @jaunty sentinel what lib do you use in python for sqlite?
sqlite3
how can i append data
How would I delete some information from a table. I am making it so when the player leaves, it deletes their information.
DELETE FROM table_name WHERE condition
Ok
how i can add in db if datatype is bigint[]
await self.bot.db.execute("UPDATE blacklist SET BlockedIdList = ($1) WHERE EventerId = ($2)", user.id, ctx.author.id)
``````cmd
File "asyncpg\protocol\prepared_stmt.pyx", line 171, in asyncpg.protocol.protocol.PreparedStatementState._encode_bind_msg
asyncpg.exceptions.DataError: invalid input for query argument $1: 499559069842014219 (a sized iterable container expected (got type 'int'))
https://www.postgresql.org/docs/current/functions-array.html, so much for just using my suggestion 
Thx
https://github.com/KetanIP/dbjson
Guys, I made a literal document database.
If you like it then don't forget to star 🌟 it.
I was not sure that it is the right place to share it, but as it is related to databases I decided to share it.
Let me know your thoughts on it.🙂
Why should anyone use that and not simply json.dump
camelcase
camelCase*
json.dump doesn’t have as much features as what they have in that package
Good work
Such as? I'm really just wondering what the benefits are.
Anyone here have experience using databases inside docker containers? I have set up an instance of PostgreSQL in docker container, and I have a container running Pgadmin4, and I have added them to the same docker network, but when I try to add my db server to pgadmin I'm getting an error that says my password is incorrect
hi! i don't know if this is the right place to ask this question, but is there something in astropy that holds the value of 1 AU (astronomical unit)?
Hey guys.
mydb = mysql.connector.connect(
host = "localhost",
user = "something",
passwd = "something",
database = "something",
auth_plugin = "caching_sha2_password"
)```
How come I get a problem on the auth plugin
NotSupportedError: Authentication plugin 'caching_sha2_password' is not supported
I searched it up and it should work.
I am using MySQL
I was able to connect. I had to change my username to postgres
help
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'case BIGINT PRIMARY KEY)' at line 2")
await temp.execute("""CREATE TABLE cases
(case BIGINT PRIMARY KEY)""")
I'm not sure, check if "case" is a reserved SQL keyword for your database
well
I've been trying to setup a database to log warns, ban information, kick information, etc. I've been recommended PostgreSQL, would you guys say it's a good first choice?
For a discord bot PostgreSQL is the standard database
But if you're really new to databases and SQL then it might be a bit confusing
sqlite is a minimalistic SQL language designed more for beginners
But because it's minimalistic there's some things you can't do with it (should be good enough though)
Also make sure you're using the async library of whatever database you choose
Ahh, I understand. I'll have a go at sqlite then, it'll probably be enough for what I need. Maybe once I get better I'll upgrade to something like PyMongo or Postgre :D
PyMongo is pretty terrible for discord bots so I wouldn't go near it for that
You wouldn't switch from SQLite to mongodb (mongodb is the database, pymongo is the driver)
Oh, erm what would that be called?
Aiosqlite and asyncpg
Ahhh
mongodb stores data very differently from SQL so switching to it would be an unnecessary pain
Thank you very much TizzySaurus and anand!
I see
Just before I head off, there aren't too many tutorials on aiosqlite compared to SQLite3.
Can I use the stuff I learn in the normal SQLite videos and use them with aiosqlite?
I think aiosqlite just needs you to await everything
most probably, just add an await before any database call
Ooh, sounds good!
@torn sphinx Thanks
@earnest parcel It was just a fun side project that I thought would be cool to make as I wanted to learn more about handling files in Python.
I have a roles table, which I want migrate to a new roles table. How I can do it with a single statement in the insert. So to select data from old table and insert into new.
Old table called roles_user is like:
id
role_id
user_id
New table called user_roles is like:
role_id
model_name
user_id
The model_name will always be the same value of User.
How would I use a variable to update a database with asyncpg?
what is it you're trying to do?
item = await self.client.db.fetchrow("SELECT ($1) FROM users WHERE userid = ($2)", item, id)
Also how would I use a dictionary?
i can't say without understanding what you want to do
Well I am trying to create the inventory like this:
items = {"1": "3", "2": "5"}
The 1 is the item id and the 3 is the value.
sure you can dump it into a text column
@autumn epoch you'd want to put it in a TEXT field, and when you retrieve it you can do json.loads on the data to get back the dictionary form
i'd explained this approach to someone else let me see if i can find it
Ok
#bot-commands message the example holds for your dictionary too
Ok
Is a list a dictionary?
Nvm
Hi, 
Do you have a kind of easy way to arrange statistics, a specific thing in the database (:
why does it show error?
if menu_prompt==2:
mycursor.execute('select * from food_type')
rows=mycursor.fetchall()
for row in rows:
print(row)
sel=eval(input('Enter your choice:'))
if sel==1:
mycursor.execute('select * from vegetarian')
rows=mycursor.fetchall()
for row in rows:
print(row)
val=eval(input('Select sno to alter price:'))
cs=eval(input('Input new price'))
ds="update vegetarian set rate='%s' where sno=%s" % (cs,val)
mycursor.execute(ds)
rows=mycursor.fetchall()
for row in rows:
print(row)
else:
mycursor.execute('select * from non_veg')
rows=mycursor.fetchall()
for row in rows:
print(row)
val=eval(input('Select sno to alter price:'))
cs=eval(input('Input new price:'))
ds="update non_veg set rate='%s' where sno=%s" % (cs,val)
mycursor.execute(ds)
mydb.commit()
mycursor.execute('select * from non_veg')
rows=mycursor.fetchall()
for row in rows:
print(row)
```
this is the code
hey how to get connection uri for a databae?
Lets say I have a sqlite database, how would I display it in a webpage for people to see, using graphs etc
at me when you respond please im leaving to general
seems quite clear as a working database
thanks, I was just about to ask for this.
how do i get the index of an object with json? For example, heres my json file. ```json
{
"users": [
{
"name": "test",
"password": "password"
},
{
"name": "test2",
"password": "pass2"
},
{
"name": "test3",
"password": "pass3"
}
]
}
json_obj["users"][2]
If you don't know the index ahead of time, there's no way to know without iterating through each of the elements in users
ok
so im thinking maybe i should do something like this:
{
"users": [
{
"test": {
"name": "test",
"password": "password"
}
},
{
"test2": {
"name": "test2",
"password": "password2"
}
},
{
"ethanedits": {
"name": "ethanedits",
"password": "password3"
}
}
]
}
so if im doing it like this, how can i retrieve the password of a user if i have the name of it. For example if i have the name ethanedits, how would i find that the password is password3
so far, this is what i tried
import json
with open('users.json') as f:
data = json.load(f)
for user in data['users']:
print(user['ethanedits'])
but this doesnt seem to work
i just get an error: KeyError: 'ethanedits'
Is it okay to ask database help here?
Should I be concerned about injection with uMongo? All items in my database are available through discord commands. Is there something I am missing?
There is nothing "confidential" or "sensitive"
What would be the best way to protect against injection, if I do need to be concerned?
@client.command(aliases=['bal', 'BAL'])
async def balance(ctx, *, member: discord.Member = None):
if member == None:
member = ctx.author
await open_account(ctx.author)
user = ctx.author
users = await get_bank_data()
wallet_amt = users[str(user.id)]["wallet"]
bank_amt = users[str(user.id)]["bank"]
em = discord.Embed(title=f"{ctx.author.name}'s' Balance" ,color = ctx.author.color)
em.add_field(name="Wallet Balance", value=wallet_amt)
em.add_field(name='Bank Balance',value=bank_amt)
em.set_thumbnail(url=ctx.author.avatar_url)
await ctx.send(embed= em)
It doesn't show the bal of other user if he is mentioned, it just shows our on >>bal and when we mention still it shows our where it is supposed to show the mentioned members... HeLp!
Yes, you get this error, because you should reference the "name" field
'ethanedits' field doesn't exist in your json
i figured it out btw, thank you though!
Ok, cool! 🙂
How to use mysql with sqlalchemy in fastapi?
Can I have a auto increasing value which I don't need to supply in sqlite
like a id for each row but I dont need to manually input it, it will automatically increase after each input
still need answer 😬
aha nice name mango db
for this you can use auto increment value
I have auto increment to the Id column but when I use my function to append the input to the db I get this error:
sqlite3.OperationalError: table learning has 2 columns but 1 values were supplied
Thanks 
Show code
import sqlite3
def append_to_db(name):
with sqlite3.connect("db2.sqlite3") as conn:
command = "INSERT INTO learning VALUES(?)"
conn.execute(command, (name,))
conn.commit()
append_to_db("Test")
After leaning you have to specify the columns still
But just only the column you want to insert
So, I need to pass the Id as None and it will handle it?.
No just you have to say which column you want to insert in
INSERT into leaning (column_name) values (?)
Like this
Ok, Thanks I'll try that
Thanks it works.
So if I am inserting values to multiple columns it should be
INSERT INTO table_name (value1, value2, value3) values (?,?,?) right?
Ok, Thanks 
I'll try to
You can select all the values and insert it to the new table by looping through the values.
I need to do with sql so can’t loop
can't use a python for loop?
No
I'll think about another way then
This is my aiosqlite database warn function:
# Create table
await connection.execute(
"""CREATE TABLE IF NOT EXISTS warn_log (
ident integer,
executor integer,
victim integer,
description text,
guild integer,
at text
)""");
id_num = random.randint(1,1000000000)
await connection.execute(f"INSERT INTO warn_log VALUES ('{id_num}', '{ctx.author.id}', '{member.id}', '{reason}', '{guild.id}', '{ny_date}')")
There's a bit more above and below, but that part seems to work just fine. I'm just so confused on why I'm getting 'column has 5 values but 6 were supplied'
sqlite3.OperationalError: table Player has 29 columns but 1 values were supplied how can i force it to ignore the other columns i just want 1 value to begin with
i want the other rows to use what was set to be Default etc
I think sql has while loops
yeah but issue is i dont know how to use it in a single statement, or what is most efficient way to do this
you do it like here #databases message
just say which columns you want to enter into
@torn sphinx it gives me that error
sqlite3.OperationalError: table Player has 29 columns but 1 values were supplied
show code
c.execute("INSERT INTO Player VALUES (?)", (discord_id))
i dont understand
@torn sphinx ```c.execute("INSERT INTO Player (Discord_Id) VALUES (?)", (discord_id))
ValueError: parameters are of unsupported type
ok now works
had to make tuple
Lets say I have a sqlite database, how would I display it in a webpage for people to see, using graphs etc. at me when you respond please im leaving to general
What about doing something like this:
INSERT INTO table2 SELECT value1,value2 FROM table1;
Thanks i will try like that
How do i create a datbase?
@opal timber.command()
async def userinfo(ctx , member:discord.Member):
roles = [role for role in member.roles]
embed=discord.embed(colour=member.colour ,timestamp = ctx.message.created_at)
embed.set_author(name = f"User info - {member}")
embed.set_thumbnail(url = member.avatar_url)
embed.set_footer(text = f" requested by {ctx.author}", icon_url = ctx.author.avatar_url)
embed.add_field(name = "ID:" , value=member.id)
embed.add_field(name = "Guild name:", value=member.display_name)
embed.add_field(name = "Created at:" , value=member.created_at.strftime("%a,%d %B %Y %I:%M %p:UTC"))
embed.add_field(name = "Joined at:" , value=member.joined_at.strftime("%a,%d %B %Y %I:%M %p:UTC"))
embed.add_field(name=f"Roles ({len(roles)})" , value=" ".join([role.mention for role in roles]))
embed.add_field(name="Top Role:",value=member.top_role.mention)
embed.add_field(name="Bot?",value=member.bot)
await ctx.send(embed=embed)
is this correct?
for userinfo?
@dense belfry
async def userinfo(ctx , member:discord.Member):
roles = [role for role in member.roles]
embed=discord.embed(colour=member.colour ,timestamp = ctx.message.created_at)
embed.set_author(name = f"User info - {member}")
embed.set_thumbnail(url = member.avatar_url)
embed.set_footer(text = f" requested by {ctx.author}", icon_url = ctx.author.avatar_url)
embed.add_field(name = "ID:" , value=member.id)
embed.add_field(name = "Guild name:", value=member.display_name)
embed.add_field(name = "Created at:" , value=member.created_at.strftime("%a,%d %B %Y %I:%M %p:UTC"))
embed.add_field(name = "Joined at:" , value=member.joined_at.strftime("%a,%d %B %Y %I:%M %p:UTC"))
embed.add_field(name=f"Roles ({len(roles)})" , value=" ".join([role.mention for role in roles]))
embed.add_field(name="Top Role:",value=member.top_role.mention)
embed.add_field(name="Bot?",value=member.bot)
await ctx.send(embed=embed)
Does anyone here know mongo because I need some quick help
How would I insert a list into mongo await warnsys.insert_one({'id_': member.id, 'guild': ctx.guild.id, 'warns': []})
doing [] just makes the value of warns null
hey i have a bit of a stupid question maybe
@burnt turret
Why is this coming back null?
This is the code:
dic = {"1": "0", "2": "0"}
await self.client.db.execute("INSERT INTO users VALUES(($1), 0, ($2))", id, str(dic))
inventory = await self.client.db.fetchrow("SELECT inventory FROM users WHERE userid = ($1)", id)
inventory = inventory[0]
print(inventory)
The inventory column is a text column
I'm getting an error of 'NoneType' object has no attribute 'fetch' on line, result = await client.db.fetch(f"SELECT prefix FROM prefix WHERE guild_id = {ctx.message.guild.id}").
I have client.db defined as client.loop.run_until_complete(create_db_pool())
create_db_pool() is defined as client.pg_con = await asyncpg.create_pool(database="Acer", user="postgres", password="(not my real pass)")
I was told my client.loop.run_until_complete is returning none, but how would I fix that?
huh i can't see a reason for that to be None when you're just inserting something there
why are you putting () around the $n though
Dont you have to do that?
no
Ok
ALTER TABLE notes ADD CONSTRAINT not_blacklisted CHECK (user_id NOT IN (SELECT user_id FROM blacklist));
Is something like this possible? i.e I want to make a check so that no data can be inserted into the notes table if the user_id exists in the blacklist table
(the above query fails, I want to know if something with the same function is available)
🤔 Do i fkey the user_id and then while INSERTing i check for ON CONFLICT
What fails
Oh right
Solved; used CREATE TRIGGER
bruh
How do you properly use ListField() from umongo?
@instance.register
class MapData(Document):
"""MapData"""
code = StringField(required=True, attribute='_id')
creator = StringField(required=True)
map_name = StringField(required=True)
posted_by = IntegerField(required=True)
type = StringField(required=True)
desc = StringField(required=True)
class Meta:
collection_name = "MapData"```
The above works, but if I change _type_ to a `ListField(required=True)`, my bot fails
Hey I use SQLAlchemy for my SQLite3 db and I don't seem to fully understand how to get data from the query when not using .all() method in the end.
Shouldn't I get only one element from the first query in message exists? How do I do it right?
def message_exists(self, api_message):
"""Checks whether the message exists or not. TODO: Maybe filter by time first and then by user?"""
query = self.db_session.query(User).filter(User.user_id == api_message.author_id)
print(query)
messages = self.get_messages_by_user_num(query.users_num)
for message in messages:
if message.content == api_message.content and message.time == api_message.time:
return True
return False
``` What `print(query)` shows
```sql
SELECT users.num AS users_num, users.user_id AS users_user_id, users.user_name AS users_user_name
FROM users
WHERE users.user_id = ?
Error message:
AttributeError: 'Query' object has no attribute 'users_num' in line messages = self.get_messages_by_user_num(query.users_num)
Looking at debugger right now, and still not sure how to get my user_num.
Hope it's fine for you that I ask for help here, admin said it's is fine when it's very specific for DB
doc1:
{ '1': 'a',
'2': [ {'20': 'b', '21': 'c'},
{'20': 'd', '21': 'f'},
{'20': 'e', '21': 'c'}
]
}
doc2:
{ '1': 'g',
'2': [ {'20': 'h', '21': 'k'},
{'20': 'i', '21': 'j'},
{'20': 'l', '21': 'c'}
]
}
say i have these documents in mongodb. and I want to list all items that have '2.21': 'c'
i.e.
{ '1': 'a', '2': [ {'20': 'b', '21': 'c'} ] },
{ '1': 'a', '2': [ {'20': 'e', '21': 'c'} ] },
{ '1': 'g', '2': [ {'20': 'l', '21': 'c'} ] }
is that possible?
probably not
I guess I have to fetch them all matching docs and then screen the sub-elements in python
hey how do i use excel cell value as input for driver.get(cellValue) to vist that url in cell. I have already imported the cell value and workbookwith openpyxl
asyncpg or psycopg2?
I've heard of both and I want to know the advantages, disadvantages if you use them
for info: I'm working on an async api.
But still want to know the pros/cons of each for most applications
@inner sentinel on the with for psycopg2 - I am not sure if asyncpg also supports it as I have not used it. So I guess you would need to do the research there.
But just juding on the name - I would say asyncpg is better than sync (psycopg2) if you work on an asnyc api ^^
ah okay
yep, go with asyncpg for an async api
How to create pymongo database
pymongo is just the driver, mongodb is the database
in the mongo shell you can just do use dbname and it'll create the database if it didnt exist already
if you're doing it through pymongo, i assume doing client["dbname"] will create that db if it didnt already exist (in this example client is an instance of pymongo.MongoClient)
I know how to do it in an UPDATE statement, but unsure how to replicate this in an event. This is what I would do in an UPDATE statementsql UPDATE economy.members AS m INNER JOIN economy.inventories AS inv ON m.user_id=inv.user_id AND m.server_id=inv.server_id INNER JOIN economy.items AS i ON i.item_id=inv.item_id SET m.bank = m.bank + m.cash, m.cash = 0 WHERE inv.item_id = i.item_id AND i.name = 'bank'So how would I replicate this in an event? This is what I have so far```sql
DELIMITER $$
CREATE TRIGGER ebanking
BEFORE UPDATE
ON members
FOR EACH ROW
BEGIN
IF 0 < new.cash THEN
new.bank = new.bank + new.cash
new.cash = 0
END IF;
END $$
DELIMITER ;```
i am saving user ID in a database i want to do it like
it still says the user's name
if this is for a discord bot, just do bot.get_user after you retrieve the id from the db
storing names are kinda pointless
Hiya,
Anyone else store money/currency values for their application not as a integer?
I have always been recommended to store currency it as an integer, but i saw some other software use varchar or float.
Hey, do you know if there is a module that has the same behaviour as Flask-SQLAlchemy but works on FastAPI?
@solemn ridge dont the fastapi docs show example of sql alchemy?
or is flask sql alchemy totally differnt?
Hey, I've got a warn command that uses aiosqlite to upload some information on a warn (reason, executor, victim, time, guild id, etc). I'd like to be able to pull up this information upon searching for a warn victims ID
This is my best shot at it:
@commands.command()
await ctx.send(results)
@commands.has_permissions(manage_messages = True)
async def warns(self, ctx, user : discord.Member):
guild = ctx.guild
connection = await aiosqlite.connect("warn_logs.db")
cursor = await connection.cursor()
await cursor.execute("SELECT * FROM warn_logs")
results = "SELECT member, executor FROM warn_logs\
WHERE member = user.id;"
The problem with this is that results is just a string lmao. Doesn't take any info out of the database :/
@torn sphinx what is the columns of the databese of yours?
like in the warns table what are the column names?
# Create table
await connection.execute(
"""CREATE TABLE IF NOT EXISTS warn_logs (
executor integer,
victim integer,
description text,
guild integer,
at text
)""");
There ya go!
lol
ok
They are my columns :D
which is the user id
Victim
ok let me try
2 mins
Victim (user being warned)
Executor (user warning the victim)
Guild (ID to make sure that you don't pull up a users warns from another guild)
at (Time)
description (reason for warn)
you can do like this
async def warns(self, ctx, user : discord.Member):
guild = ctx.guild
connection = await aiosqlite.connect("warn_logs.db")
cursor = await cursor.execute("SELECT * FROM warn_logs where victim = ?", (member.id,))
results = cursor.fetchall()
results is a list of all the worm items in the database for that member id
you can make loop through this to print it however you like
Ohh
Hmm, not entirely sure how to do that.
where do you want to print it?
I'd get it to print in an embed
For e.g.
I pull up your warns in my server and it checks that the guild the warn was set in == the one it was requested in
It would then display who warned you, when, why, etc
embed = discord.Embed()
for warn in results:
executor = warn[0],
victim = warn[1],
description = warn[2],
guild = warn[3],
at = warn[4]
embed.add_field(here add details)
await ctx.send(embed=embed)
you can loop like this
each time you loop it is 1 row from the results
understand?
Ooh, I think so
Why are there [0], [1], etc at the end of the variables?
because you have 5 columns in the table
0 is the value of first column, 1 is value of second like this
Ohh, understood.
Apologies, I'm quite new to databases. But thank you so much for the help
Been looking to find a proper answer for days now lmao
yeah no problem man ahaha we are all new, lmao i also had a question posted before above as well still wait for reply
let me just bump it in case anyone missed it
It is kind of different, flask-sqlalchemy has a simple setup and it helps u get coding immediately
how can i prevent sql injection attack in mysql.connector
c.execute('INSERT INTO ranks(id,xp,messages) VALUES (?,?,?)',
(5555, 5555, 5555,))```
keeps giving
```mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement
i think the placeholder you use with mysql connector is %s?
isnt that also string formatting
it is if you used it like
"string %s" % arg1
``` or something along those lines
its been a while since i've used mysql-connector but i think it uses the same %s as the placeholder
but passes the arguments separately in a tuple as you've done
so i wud
https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html the doc seems to confirm
c.execute('INSERT INTO ranks(id,xp,messages) VALUES (%s,%s,%s)',
(5555, 5555, 5555,))```
i think that should work
👍
making like a DB with txt files is considered a DB?
probably yeah if is organised data
ok i am doing one, when i finish i will send it to see if theres any trick or easiest way to do it
is postgres soutable for large bots?
yes
ooh
can I transfer my db info form sqlite to that?
likethe info?
When designing the data layer using something like repository services, which use abstract classes, how can the connection be abstracted?
like should service implementation be aware of how the database connection is made or do we just pass a connection object to the class?
yeh
how?
i dont know how exactly but i know you can 😅
i think you can dump a sql file of the data and then import it into postgres
maybe you have to modify it a little because i think postgres has some different syntax
for outputs from a pg_dump, doing something like psql databasename < output.sql works i think
but then pg_dump outputs SQL queries i suppose
Posted more detail in #software-architecture if someone wants to see take a look
can you set two things in an sqlite UPDATE SET? like
db = sqlite3.connect('mydb.sqlite')
c = db.cursor()
c.execute("UPDATE table SET thing1 = ? and thing2 = ? WHERE key = ?", (thing1Var, thing2Var, keyVar,))
db.commit()
c.close()
db.close()
yeah
sweet, thanks.
can I cache stuff with postgres?
Hello
.
Let's say I want to commit something, is it expensive (as in does it take time)?
If it is, would it be better to have a task that commits every now and again or would it be best to commit after every modification?
This is for sqlite btw
Can I ask questions about json here?
hi guys, im trying to get a jsonb string, but i want to select null if list is default value of this column, how can i do this, im using postgresql
Any good database resources
if [z for z in maindb.find({"link": {"$exists": True}})]:
print("hello, world")
``` @torn sphinx i think this is what you're asking, not completely sure what you mean tho
Hello Everyone Whats The Craic
does anyone know how to unlock an sqlite database?
I am scraping items 22500 of them, could someone recommend a time efficient way to check if their id would be already inside my db?
Hey data nerds, If anyone could provide me some help in the #help-cherries channel I'd appreciate it #help-cherries message
how do I cache stuff into memory with postgresql
I'm having trouble with import pyodbc. can anyone help?
what is the error message?
Hi, I'm using mongo and am trying to list all items in a collection, I can't iter through them though, what do I use?
Please ping me when responding
you can iterate through collection.find()
Oh I see, thanks
np
anyone know if their is a mypy plugin / something related that checks if sql strings are valid, either based on its own syntax validation or (even better if its out there) against a running database?
like sqlx in rust, which checks if sql query strings are well-formed at compile-time by validating them against the database reached at a certain URL
this keeps happening it says inf by None
@commands.command(aliases=['inf'])
@commands.has_permissions(kick_members = True)
async def infractions(self ,ctx , user : discord.Member = None):
if user is None:
user = ctx.author
'''
Displays the person's infractions similar to Modlogs
'''
async with asqlite.connect('modlogs.db') as conn:
async with conn.cursor() as cursor:
query = f"SELECT * FROM Modlogs WHERE user_id = ? AND guild_id = ?"
await cursor.execute(query , (str(user.id), (str(ctx.guild.id))))
result = await cursor.fetchall()
localem = discord.Embed(name = f"Infractions Of {user}" , color=discord.Color(0x2FBDFF))
localem.add_field(name =f"All infractions of {user.name}" , value = "All the infractions of the given user")
for row in result:
infid , guildthing ,mod_name,reasonthing, use_namer, time , command = row
user = self.client.get_user(mod_name)
localem.add_field(name =f"Infraction By {user} ID : {infid}" , value = f"Type: {command} \n Reason: {reasonthing} \nAt: {time}" , inline=False)
await ctx.send(f"**{len(result)} Logs Found**")
await ctx.send(embed = localem)
if len(result) == 0:
localem.add_field(name = "Empty Void" , value = "Its all Empty" , inline=False)
await ctx.send(embed = localem)
code
I have two separate applications and one of them is constantly updating a value and I need the other application to retrieve that value. Is there any quick way to do this without going through the whole mySQL setup.
let those two apps communicate maybe
that server is yours?
yes
genuinely asking how is this related to databases
so like I could set up a mysql database for the two applications to talk to each other
but I would have to watch a 30 minute video on how to do that + download mysql
I was wondering if there was some alternative to this
Hi, i just started django. After migrating the db, this was all generated by django, do i need all of this? I just want to have my own personal table
im using mysql btw
I believe Django needs all this
dang, i feel like im making this too hard on myself instead of using php as back-end?
You don't really have to manage those tables though I think? Django just needs those to keep track of migrations and other internals I think
You can just use the models you make and not really bother about these is what I think (I may be wrong though)
the three columns exists still i am getting this error
any idea why this is happening
aight thanks for answering ❤️
It's supposed to be in one set of parentheses (don't wrap each item in a (), put all three in one)
okay
async def notify_user(self, tags, embed):
db_user = sqlite3.connect('./cogs/database/users.sqlite')
cursor_user = db_user.cursor()
authors = set()
results = []
for tag in tags:
cursor_user.execute(f"SELECT AUTHOR_ID FROM follow WHERE TAG_NAME = {tag}")
result_user = cursor_user.fetchall()
if not result_user:
db_user.commit()
db_user.close()
return
results.append(result_user)
for i in range(len(results)):
for j in range(len(results[i])):
for k in range(len(results[i][j])):
authors.add(results[i][j][k])
it says no column i in line 36 which is cursor_user.execute(f"SELECT AUTHOR_ID FROM follow WHERE TAG_NAME = {tag}")
Can I somehow do UPDATE [...] SET [...] WHERE [...] but if entry doesn't exist it will do INSERT INTO [...]
?
how to fix this?
On postgres, that (upserting) can be done with INSERT .... ON CONFLICT DO UPDATE ...
That error is being raised because there are no quotes around your {tag}, so SQL thinks it is a column
BUT- don't go adding quotes now
lol
db_user = sqlite3.connect('./cogs/database/users.sqlite')
cursor_user = db_user.cursor()
cursor_user.execute(f"SELECT AUTHOR_ID FROM follow")
result_user = cursor_user.fetchall()
authors = set()
for i in range(len(result_user)):
for j in range(len(result_user[i])):
authors.add(result_user[i][j])
for tag in tags:
for author in authors:
author = await self.client.fetch_user(int(author))
try:
channel = await author.create_dm()
await channel.send(embed=box)
except discord.DiscordException:
print(f"Can't dm {author}")
ok so here after I edit it it works but sends a message each time it finds tag in db so instead of sending it once to each user each time it find a tag it sends message (is this better in anyway)?
i'll remove f string
Hey, I've been using a warn command, but when I warn someone for the second time, it rewrites a row in a table. This is my code for context:
# Define connection and cursor
connection = await aiosqlite.connect("warning_log.db")
# Create cursor
cursor = await connection.cursor()
# Create table
await connection.execute(
"""CREATE TABLE IF NOT EXISTS warning_log (
warnid integer,
executor integer,
victim integer,
description text,
guild integer,
at text
)""");
sqlStuff = """
INSERT INTO warning_log (warnid, executor, victim, description, guild, at)
VALUES (?, ?, ?, ?, ?, ?)
"""
warn_id = random.randint(1, 1000000000)
await cursor.execute(sqlStuff, (warn_id, ctx.author.id, member.id, reason, guild.id, ny_date,))
await connection.commit()
await connection.close()
Im using MySQL. Can i do UPDATE [...] ON CONFLICT DO INSERT [...] ?
Ah I'm not familiar enough with mysql to answer
Try googling "MySQL upsert" (sorry, kinda busy rn or would've tried finding an answer myself)
Are you sure that there are no UPDATE anywhere?
i have nice tkinter + mysql login page
how can i make sure it secured
im not going to run it but i want to practice security
You can check some OWASP guidelines with SQL injection
ima check it thank you 🙂
Good luck!
ok I will just check if it exist
Apologies for the late reply. No there are no 'UPDATES'
Oh I think I know why
It can only display one variable
lol
Oh dear, how will I fix that
Don't worry
I don't have any experience with aiosqlite 😦
@commands.Cog.listener()
async def on_ready(self):
async with aiosqlite.connect("eco.db") as db:
async with db.execute("SELECT * FROM eco") as cursor:
row = await cursor.fetchone()
for guild in self.bot.guilds:
for member in guild.members:
if await db.execute(f"SELECT id FROM eco WHERE id =?", member.id):
if row is None:
await db.execute(f"INSERT INTO eco(name, id, cash) VALUES ('{member}', {member.id}, 0)")
else:
pass
await db.commit()
print('database online')
sqlite3.OperationalError: no such table: eco
help me 😦
Are you sure you have a table called eco
The error tells you there's no table like that
hi
hi
k
How would I set up a database for a user's money/currency (For discord.py)
It depends on the type of database you choose and how many servers your bot is in. I would recomment sqlite for something like that. There are plenty of youtube tutorials on how to use it with python.
My bot is probably just going to be using one server, and I am probably going to use the replit db, it's just I don't know where to start.
@wind trench if you want easier way to use aiosqlite, consider using https://github.com/codemation/aiopyql
I've never used that before, so I don't have a direct answer, but I'd start with figuring out exactly which values you need to store and creating columns for them. For a currency bot, you would at least need a column with an identifier for each user (their id is a good option) and a column for their balance. If you want to have a wallet seperate from a bank account or something, that would also need to be included. Then learn how to create new rows in the db and how to edit existing ones. I think repl has a guide for their db with python.
PyMongo:
I want to update my one document. I want to set a key with a value (ban, time) after unset all keys with their values except for _id and ban.
I am noob and dumb, pls help.
collection.update_one({"_id":object.id}, {"$set":{"ban":expiration}}, {"$unset":{"$nin"["_id":1,"ban":1]}})
eck
help pls
I have database called database and table called info in the table there is
Id username password privilege
Now 2 questions
Can I add new column called teachers
And 2 can I assign multiplie teacher to the column
yeah
maybe? what do you mean can you give example
hey
i need help
for upgrading my ai
can any one help me?
as example i have a user called mark his password is mark123 his privilege is student and the teachers that learn him are michal,moran,eti
and is michal, moran, eti also users in your database?
ok but my english is not so good for explaining 😅
I am creating my discord.py bot with PyMongo. I want to create a block system.
I want to update my one document. I want to set a key with a value (ban, time) after unset all keys with their values except for _id and ban.
I am noob and dumb, pls help.
collection.update_one({"_id":object.id}, {"$set":{"ban":expiration}}, {"$unset":{"$nin"["_id":1,"ban":1]}})
help pls
plsss
How do i unset all keys with their values except for some keys in one document MongoDB?
can you try
collection.update_one({"_id":object.id}, {"$set":{"ban":expiration}}, {"$unset":{"$nin"["_id","ban"]}})
TypeError: string indices must be integers @burnt turret
TypeError: upsert must be True or False
XD
SELECT playerid FROM participants where 92 BETWEEN start and end
So, this query works fine for any number over 100..
But when it's between 1 and 100 , it doesn't return any rows? Why?
huh you don't seem to be passing an upsert though, are you?
i dont lol...
Any help
collection.update_one({"_id":object.id}, {"$set":{"ban":expiration}})
collection.update_one({"_id":object.id}, {"$unset":{"$nin":["_id","ban"]}})
this works
but it doesnt remove other keys
{"$unset":{"$nin":["_id","ban"]}} doesnt work
they may be custom
ah dammit
i'm not sure how you'd do that, i haven't used unset in that manner before
if you find no other way i guess you could just delete and then insert instead of an update
but that's worst-case scenario
yeah...
Appreciate if anyone can help me understand this
So first off all the playerids are the same
you should get 1 record back.
classes
- class_id = int ai
- class_name = varchat 255
users
- user_id = int ai
- username = varchat 255
- password = varchat 255
- role = varchat 255
user_classes
- id = int ai
- user_id = same as in users
- class_id = same in classes
i did something like this
ai means like random number it grows by one everytime
i have some questions.
1 how do i make the user_id in user_classes to be same as in users
2 how do i add the msg table
3 how do i add the grade table
its for school-login-register-msg-grade system
I am not getting output..
how about select * ? do you get anything?
1-100 any number, no output
others i do get it
do you want the overlap?
also whats the datatype of start/end
TEXT
WELL YEAH
but it works in some cases...
you need to parse it as an int
because text can compute to a number, but not the way you think
i need help pls
This doesnt work
SELECT playerid FROM participants where 92 BETWEEN start and end
This works
SELECT playerid FROM participants where 250 BETWEEN start and end
Don't think it can be a data type issue
is there anyway to change the default value of _id so its a smaller string?
so for example,
if each value within the database will have an ID which relates to its number
so
first piece of data inserted will be 1, second will be 2 etc etc
you can add your own _id while inserting
but afaik mongodb doesn't have a simple way to autoincrement the way you've described
dang, alright. Thanks a bunch 🙂
I guess ill just leave it and if i ever get to 500mb ill decide what to do
I was trying to host a mongodb locally on my raspberrypi but couldnt figure it out
hello, trying to create a pen and papper rpg game with discord.py and was thinking about which database to use and thought about sqlite3
easy to handle database is what I was looking for
MySQL easy too
Also
Speaking of MySQL This statement gives me error of syntax
Alter table Guess Add(Lock int Default 0)
How would you reference your main table that ties to all other tables say in a stock database or something
Just curious what term to use in my mind
Uh
Key table? Legend table?
Just Name of the bot
Or name of the program
Or database
Btw rusty
Alter table Guess Add Lock int Default 0
uwotm8
Can u help @pure dirge this thing giving me syntax error
Alter table Guess Add Lock int Default 0;
Oh I'm a noob I can't help sorry lol
;-;
I'm just learning how to make databases
@mortal scarab
yes
it suppse to be some kind of login/msg/grades system
do you think those table will do?
i will need some more info on that
ok one second
main screen
than 3 buttons
then 3 screens(admin login,teacher login,student login
if you login as admin then you move to admin_sesh screen which means you have 3 buttons (insert new user,delete existing user, logout)
insert new user is inserting user to db
delete existing user delete user from db
logout moves to main screen again
for here that whats working
than i wanna make:
teacher login(already working the login) that if your information is right you are moving to teacher_sesh screen which has 3 button(send msg to student,update grades,logout)
send msg to student should have some kind of form with, name of student(from drop menu),text of msg, SUBMIT button. the msg need to be stored on database in new table called msg and i would save a var of the id of the msg so i cant later print it in the student_sesh screen
update grades which i havent think of yet
logout - you know what
student login(already working login system) that if your information is right you are moving to student_sesh screen which has 4 buttons
check grades: you move to new screen that have your grades and class name on the side
check new msg: you move to new screen that have teachers name and msg (if you have)
send msg to teacher: same as send msg to student but upside down.
logout - you know what
im trying to think on a way for the msg and grade system as my login,delete,insert already working
btw all this screen stuff in on tkinter
@carmine totem u will need a table with the UID, CID, role,
so like move role from table users to users_classes ?
if you can maybe explain not only say the answer i would like to
as teachers wont have classes thy wont need CID so null but students will have so u place values
admim will also be not assigned CID
class for teacher will be what class they are teaching
so like if there is username=Eti123,role=teacher,class=math that means she TEACHES math
but if there is username=mark1,role=student,class=math,arabic,english
then he is in 3 classes
students can be in multiple and teacher only teach one
ohh so rather remove the CID and implement a ClassAssigned column
wait what
can u like maybe overwrite on the db design i sent
cause i cant understand
ok
thank you very much 🙏🏻
ok wath data fields do u have gimme tat
what
UID and stuff
when registering new user on admin menu
u need
username
pass
role (drop menu on teacher/student)
class(check box)
that all
the mag and grade stuff
mmm have you read this
like it has everything explained there
when you login as admin you can insert new user which i said here
i like need exact fieldes u need
when u login as teacher u can either send msg to all student in your class(insert msg_content to db & select from role=student, class=class name of the teacher)
also you have grades which is basicly the same thing
but for each person
not to all student
its like private msg of grade
also when ur a student you can send msg to teacher
and watch grades with print your grades
@carmine totem how many classes do u have
sorry i do not understand what ur askin
@carmine totem uk classes each student takes
uk?
You know
so like each student takes idk 3 classes
math,english,arabic
each teacher teaches one
ok
so like math teacher should be able to send msg to mark(cause he learns math,english,arabic)
then he should see
it
for that to happend u need to store student classes, msg content,msg sender,username of msg getter
right?
and also id of sender cause y not
uid = user id
suid = sender id
r = reciver id
sender reciever
ok let me try and understand it
thank you ofcourse
you dont save the username?
i think it should be added in UserTable
as he need to login with his username
its easy u have a main user table that stores unique users,
thers a grade table with FK uids and stores grades and subjects corresponding to them ,
hten theres the message log that u will fill up \
@carmine totem u can add that in user tble but dont use username as a PK
Foreign key
yes
u should handle conditional logic with the queries rather than implementing them in DB design
and my suggestion will be encoding the classes like a 4 digit number 0111 it from 4 subjexts u use 3
and for UID use (A, T, S)-9 digit number
so u elimanate the role column
and then as example user id 1 username mark password mark123 role student classes math arabic
then user id 2 username moran password 1604 role teacher classes math
if she wanna send msg then what will be sql code?
selece from usertable where role=student class=math (how class going to work?[maybe if i do 'math in class?] entry for msg content that stores on msg then suid is userid(cause she is logged ez) and ruid(how we gonna know this?)
then when student logs in we check if there is msg with his rUID if so print on screen
please answer my question if you know how 🙂
so u asking U1 will send msg to U2
INSERT INTO msg (rUID, sUID, msg, time) VALUES ( select UID from UserTable where username == 'U2', U1, "HELLO", timestamp)```
@carmine totem
but can i make sUID aka man that is logged in choose rUID by his name?
then i will add full_name to db
then when send msg u have entry:
text = place to type your text
reciver name = list of names then you can choose which one you sending to
by list of name i mean dropmenu
so you have option
u choose
it stores rUID by recviver name, it stores text by msg and that it?
@mortal scarab
@carmine totem yeah that query does that
How can I insert variables into sqlite execute commands>
c.execute('''CREATE TABLE {varname} (
What’s question ?
What is Checkbutton?
So first make sure you are getting the value in correct way
im not
Try printing value you get
First you need to work out how to get the value then you can proceed to insert in database
this is my db ok
im also having this gui
in order to know wheter someone in those class or not
i did onvalue='yes' offvalue='no'
then i saved it as var
code
we talking bout add_user_to_db
and add_user
so my error is why am i not getting any no/yes in the last 3 colums in db
Please tag me when answering
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="test111",
password="test"
)
print(mydb)
mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'localhost:3306' (10061 No connection could be made because the target machine actively refused it) ???
so I've looked at asyncpg, but is there a similar library that is sync
TL;DR: What's the equivalent of an INNER JOIN for use in a event/trigger?
I know how to do it in an UPDATE statement, but unsure how to replicate this in an event. This is what I would do in an UPDATE statementsql UPDATE economy.members AS m INNER JOIN economy.inventories AS inv ON m.user_id=inv.user_id AND m.server_id=inv.server_id INNER JOIN economy.items AS i ON i.item_id=inv.item_id SET m.bank = m.bank + m.cash, m.cash = 0 WHERE inv.item_id = i.item_id AND i.name = 'bank'So how would I replicate this in an event? This is what I have so far```sql
DELIMITER $$
CREATE TRIGGER ebanking
BEFORE UPDATE
ON members
FOR EACH ROW
BEGIN
IF 0 < new.cash THEN
new.bank = new.bank + new.cash
new.cash = 0
END IF;
END $$
DELIMITER ;```
Why is this throwing this error?
Try INTEGER instead of INT
👍
it works, thanks very much!
Anybody here have any experience in local mongodb databases? Having quite a few issues:
what Bd?
finally working
it took me some time
but eventually yessss
@torn sphinx that what i did to determine wheater someone in class or no
i did something so dumb
but eventually it worked
Nice
global math
global english
global arabic
math = ttk.Checkbutton(screen5,text='math',variable='math_yes_or_no',onvalue='yes',offvalue='no')
math.place(x=100,y=147)
english = ttk.Checkbutton(screen5,text='english',variable='english_yes_or_no',onvalue='yes',offvalue='no')
english.place(x=160,y=147)
arabic = ttk.Checkbutton(screen5,text='arabic',variable='arabic_yes_or_no',onvalue='yes',offvalue='no')
arabic.place(x=240,y=147)
global math1
global english1
global arabic1
math1 = StringVar()
english1 = StringVar()
arabic1 = StringVar()
math1 = math.state()
english1 = english.state()
arabic1 = arabic.state()
global math_value
global english_value
global arabic_value
if 'selected' in math1:
math_value = 'yes'
else:
math_value = 'no'
if 'selected' in english1:
english_value = 'yes'
else:
english_value = 'no'
if 'selected' in arabic1:
arabic_value = 'yes'
else:
arabic_value = 'no'
thank you
Might be quicker to use 1 and 0 for yes and no
@carmine totem SQLite supports boolean values. You can just store True and False
nevermind, it doesn't
🤔
but if you want, you can use sqlite3's more advanced features to create your own datatypes
MySQL error: Can't connect to MySQL server on '127.0.0.1' (10061) Pls help
@fallen bone sounds like your mysql server isn't running on the computer or server where you tried to run it
Thanks I will check out
hello when every i open my python file it just closes rightaway
youve asked this on multiple channels now, ask in one. (its because your getting an error)
ccursor.execute("CREATE TABLE EMPLOYEES (idemp int NOT NULL AUTO_INCREMENT PRIMARY KEY, fname VARCHAR(20), lname VARCHAR(20), datbirth date,timbirth TIME, childnum int(20), adremp text(258), numcard bigint(65535), salaryyemp numeric , contract boolean)")```
out of range why?
MySQL error: Can't connect to MySQL server on '127.0.0.1' (10061) Pls help
where is the databasee?
import mysql.connector
mydb = mysql.connector.connect(
host="127.0.0.1",
user="test111",
password="test"
)
print(mydb)
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")
This is what I have
and mysql is running on the same machine, or a container or where?
on my machine
try
mydb = mysql.connector.connect(
host="127.0.0.1",
port=3306,
user="test111",
password="test"
)
Hey folks, I've made a warehouse management system and I was wondering if anyone could give me feedback on it?
Hi, I facing some issues regarding Django database. When I tried to run, it prompt "No Such Table on XXX". Solution that i have taken: 1. Python manage.py make migrations/ migrate . 2. Make sure the APP added into INSTALLED_APP. 3. Delete entire migrations done and re-done the step 1
sadly doesnt work
I get this
Is this how json works. its my first time using it.
perms = {811935502059569152, 811935502059569152}
with open("sample.json", "w") as outfile:
outfile.write(json.dumps(perms, indent = 4))
I have a take home assignment for a job interview that requests a locally deployable database (it's setting up a super simple but self contained API). I've usually used mongo or aws, what is the simplest and lightest solution for this? My short googling has landed on Sqlite3.
@burnt turret 👋 If I was to use aiosqlite, would it be best to commit once you've done whatever or use a task to commit periodically?
Ah I haven't had to think about this much personally, but I think committing immedietely would be better right? Otherwise anytime you access data before the task has committed the changes, you'd be accessing old data
yea
That's true actually
Thanks!
I was just wondering because I thought it might be expensive/time consuming lol
oh, does committing take too long?
I've been using asyncpg and it autocommits after every operation 
I don't think so, I'm yet to use aiosqlite yet lol
I was just reading up on the documentation ahead of tomorrow
how do i check if username already exist
using mysql
Right, I don't think committing is a very expensive operation (but I may be wrong on this)
the username i wanna check stored as username
Alright, thank you again!
you have a table with a column containing usernames?
yes
data base name is database
table is users
and column is username
dont mind the other staff
so you could do SELECT username FROM users where username=<some username you want to check> and then if the query returns something, it means the username exists?
if you want all the columns, do SELECT * ...
if the username i want to check is stored as var called username
than code will be
query_vals = (username)
handler.execute('SELECT username FROM users where username=%s',query_vals)
am i right or mad wrong
really close actually
only problem is that query_vals needs to be a tuple - and to define single element tuples, you need to put a comma at the end
(username,)
oh ok yeah
realy close indeed
thank you let me try
def error_on_insert_user_username_in_use():
quary_vals = (username,)
username_check = handler.execute('SELECT uesrname FROM users WHERE username = username',query_vals)
if username_check != 0:
text_label = Label(screen5, text=username + ' is taken \n please choose new one', bg="yellow", fg='black', width="22", height="3",
font=("Helvetica", 13))
text_label.place(x=102, y=170)
error_in_insert()
screen5.update()
screen5.after(2500, text_label.destroy())
else:
error_on_insert_user_password_too_ez_to_guess
why error?
oh uesrname
found it
your if statement is a little off btw, username_check will never be equal to 0 really
wait a minute, let me refer the docs
👍🏻 👍🏻
huh, the site doesn't seem to load for me
So I may be wrong here but that will mostly be a Cursor object?
Let me read the doc again then, it's been a while since I've used this and I don't wanna give you incorrect info😅
okay so in your case db is the connection object, and handler is a Cursor object.
after executing the query, the result set is stored in the Cursor object, i.e handler
Now to actually get the values from it, you have to use a fetch method
data = handler.fetchall()
This takes all the rows which had matched your query, and assigns it to the variable data
You can check if the len of this is 0 -> this would happen only if no rows matched your query
there are other fetch methods, like fetchone, fetchmany etc
Actually what would be better in your case is handler.rowcount - this directly gives you the number of rows that matched your query
if handler.rowcount != 0:
do something
ok thank you so much
def error_on_insert_user_username_in_use():
quary_vals = (username,)
username_check = handler.execute('SELECT username FROM users WHERE username = username',query_vals)
if handler.rowcount != 0:
text_label = Label(screen5, text=username + ' is taken \n please choose new one', bg="yellow", fg='black', width="22", height="3",
font=("Helvetica", 13))
text_label.place(x=102, y=170)
error_in_insert()
screen5.update()
screen5.after(2500, text_label.destroy())
else:
error_on_insert_user_password_too_ez_to_guess
thats weird
