#databases
1 messages · Page 44 of 1
should I have an entities table and a categories table that has (entity_id, category name) that would just be a list of the associations between categories or..?
thanks!
Yeah, so what you're referring to is a join table
It depends on the kind of relationship you need to have with your data
If you need to be able to go from entity to category, and also from category to entity, and there might be more than one relationship for either of those situations, then you do need a join table
a join table is basically just an extra table with three columns
a primary key ID, and two IDs - one each for each table you're associating
so ID, entity ID, category ID
if you're using an ORM, that's likely to be quite easy to do in it
Ohh that makes total sense
Thanks
Can you look over some models for me in a bit? @viral crag
coming from the PHP-world, just started with python: which DB-engine would u suggest using?
MongoDB? NoSQL?
just to keep it short:
I wanna check some routine every 5 mins and insert / update some records everytime.
not talking about many records... lets say 100 or so
That's not what I meant
It depends how strict your schema enforcement needs to be, and how data in your tables relates to data from other tables
not strict as all, only 1 table probably without any relations
at least for now - it might expand later, but just for now
i'll check out RethinkDB
thanks
@astral blaze mariadb or mysql works fine for simple stuff
i'm familiar with mysql, just wasn't sure if it is the "way to go" with python
will do, thanks for the input 😃
I mean if it's only one table just use sqlite
hey just wanted to say SQLbolt is helping me learn SQL a lot
it's somewhat mobile friendly so i get on it while im on the toilet too
Classy
(you're more likely to get responses if you give the details up front, unfortunately we humans are lazy and if people feel like they have to extract the situation out of you they're less likely to bother with helping)
maybe you could provide us with some details like your operating system, the method you're using, and the particular troubles
haha no problem
please could someone help me figure out the issue i'm having with installing mysql server on windows 7?
during the configuration part of the install, it's failing to initialize database. i get warnings, but no actual errors that i can identify. actually when i installed this earlier today i managed to get to the 'starting server' portion of the config but it said it was taking too long and i didn't understand why. i decided to reinstall and now i'm getting this initializing database failed error message.
this is the .ini that people seem to ask for on stackoverflow altho it doesn't include the log which i'm not sure how to find.
https://pastebin.com/TfphSDHn
i'm going to restart my pc and do a clean install of mysql server again and see what happens, but this will be the 3rd time i've tried it this way...
yeah, a fresh install did it, annoyingly. i have learned nothing except that i hate mysql 😂
F
what do you guys think of Peewee as an ORM?
seems nice
It's not great, but it works
it's kind of like django, right?
I don't know peewee but the django ORM is okay, so I guess I'd feel the same about peewee
I've heard they're more or less the same.
Why would I choose Peewee over SQLAlchemy though? SQLAlchemy seems far more mature
Peewee is smaller and comes with a migration framework
there's also peewee-async
but to be honest, SQLA has a nicer api, and alembic is way better than peewee's migration features
Just leaving this here: https://www.influxdata.com/
Hello, I am looking for a nice way to log live data to something other than a csv file. Any ideas on the best way to get started with databases like a simple tutorial
If you're logging live data, are you sure a database is what you want?
I mean, what you're asking for is a bit ambiguous
Are you storing time-series data? Or are you talking about aggregating log messages?
why not store them as a file with an about.txt that holds the 12 variables?
@viral crag I am storing 120 currency pairs with 12 variables each approximately. My current saving method is to just save my latest dataframe once it reaches a count of 24 hours
However for backtesting purposes I like to review past data in graphs instead of raw data. I was hoping if I store my data in a database vs a csv excel file I would be able to have a gui for the database so I can easily view historic data
@steel slate I was using csv files before and it works. However I just set it to save once it hits a count of 24 hours. Im not sure how to update a csv file with the last line of a dataframe
So you're storing.. What exactly?
That didn't really answer my question
Transactions? Totals?
Live stock ticker data
"e": "24hrTicker", # Event type
"E": 123456789, # Event time
"s": "BNBBTC", # Symbol
"p": "0.0015", # Price change
"P": "250.00", # Price change percent
"w": "0.0018", # Weighted average price
"x": "0.0009", # Previous day's close price
"c": "0.0025", # Current day's close price
"Q": "10", # Close trade's quantity
"b": "0.0024", # Best bid price
"B": "10", # Bid bid quantity
"a": "0.0026", # Best ask price
"A": "100", # Best ask quantity
"o": "0.0010", # Open price
"h": "0.0025", # High price
"l": "0.0010", # Low price
"v": "10000", # Total traded base asset volume
"q": "18", # Total traded quote asset volume
"O": 0, # Statistics open time
"C": 86400000, # Statistics close time
"F": 0, # First trade ID
"L": 18150, # Last trade Id
"n": 18151 # Total number of trades
I also store current coin counts and calculated netWorth in lists. Also trade positions
gdude, what he wants is to store live-streamed data from a stock-exchange/brokerage/data-provider which is to be used for later research on the data. Maybe there is real-time calculations + plotting involved too
Ideally one would want a csv like file for each ticker and also for each day or week or month ( as maybe convenient). Smaller chunks are easier. I have no idea about databases. So not sure if databases are better to text dumps
Databases can be queried, which is the point
It sounds like what you want is something like rdb
A timeseries database with incremental backoff over time
A little off-topic. After a little background study, it appears that the data he posted is level 2 data compared to level 1 which is just the prices. Some basic reading suggests people mostly use level 2 data for HFT algorithm trading. Pretty expensive given that they say HFT is only workable if you have a workstation close to the exchange i.e. high real estate costs leading to high price for your hired e-space. If those are for crypto-coins rather than real world currency-pairs ( USD-JPY or USD-EUR) you speak of, then it is a different game I guess
definitely crypto:
"s": "BNBBTC", # Symbol Indicated Binance Coin to Bitcoin trading.
its crypto. And its not hft, its algo trading
@desert ice you explained what i meant pretty well
my bot is alreary in papet and live trading however it was just in level 1 data tgrough api calls. The next stagr of development is to go to level 2 websocket live stresm
How can I build a database with sqlite with information about songs like singer, titel, date of release etc. ?
i'm sorry i can't help you
@torn sphinx just do it like you would do it in normal sql databases, if you dont know what those are/how they work do a bit googling, basic sql is really easy to learn
so I could learn from this
but it says at this site you sent that this tutorial is for mysql, .... but not for sqlite
sql syntax is quite similar
there are only very specifc things which are different
INSERT INTO, SELECT FROM, UPDATE and ALTER should always work in all dbs
and if you are using sqlite i doubt you need much more if any
and once you learnt basic syntax you just go for https://docs.python.org/3/library/sqlite3.html
i can come up with some sql to make one
CREATE TABLE Players
(
"id" SERIAL PRIMARY KEY NOT NULL,
"nick" TEXT NOT NULL,
"email" TEXT NOT NULL,
"progress" TEXT DEFAULT '{}' NOT NULL,
"alliance" int DEFAULT 0 NOT NULL,
"bio" TEXT
);
although i am not sure if sqlite has the "TEXT" datatype
so this is just a table right?
yes
it says invalid syntax when I run it
does it
well i guess thats too postgresql then
CREATE TABLE humans (date text, name text, age real)
postgresql?
another sql database
take a look at this https://docs.python.org/3.6/library/sqlite3.html @torn sphinx
This is so long
so is anyone in here good with sqlite and can create databases with sqlite?
I really need your help
it'll be enough for sure
literally read the docs linked
Hi. Can someone help me to put together a request for sqlLite?
DB is very simple. One column with numeric User_Id where each user has his own table with numbers
Looks like
[
00001 [001, 002, 003 ...]
00002 [001, 002 ...]
00003 [001, 003, 005 ...]
...
]
Is it the right choice of DB structure in terms of performance?
I need to fill out the database with data structured in the same way in local variables.
Users should not be duplicated in dB. In case if user already exists, simply add the numbers to his table.
That's how I suppose to do it.
for u in user:
users_cursor.execute ("INSERT INTO users [id] VALUES [", u[0],"] IF NOT EXISTS")
for num in u [1]:
users_cursor.execute ("INSERT", num, "IN .... IF NOT EXISTS WHERE id =", u[0])
Is there any option to add everything in one line?
(I'm not that much experienced with databases, so I would be grateful for help)
instead of looping over .execute, you should just compile these lines into a single string with semicolons seperating each instruction and then execute when you're done looping. that way you're just making one database interaction instead of len(users) * len(u[1]) database interactions.
this is a bigger problem with other databases, though
sqllite is usually a local file, but if you were using a remote database, for example, using this approach might mean having to send data over a network 1000 times instead of 1.
I'm afraid I don't know any truer ways of making it one line off the top of my head, though.
Each user has their own table, what?
there could be a lot of numbers related to each user, I thought to use string instead of table, but it doesn't seem to be the right solution
any better ideas?
A table per user isn't a good idea
I'm unsure as to what you're doing to suggest a better alternative mind
A condition is easy accessibility of all numbers of the specified user.
I can put them all in one column, with a duplicated user id. I do not know if this method is better. In the long term, one more table will be needed, where each number of the user is assigned another array of numbers. And also an additional info.
Like:
u1, somedata, [num1, num2, num3...]
somedata somedata somedata
[subnum1 [subnum1 [subnum1
subnum2 subnum2 subnum2
subnum3 subnum3 subnum3
... ] ...] ...]
u2, somedata, [num1, num2, num3...]
somedata somedata somedata
[subnum1 [subnum1 [subnum1
subnum2 subnum2 subnum2
subnum3 subnum3 subnum3
... ] ...] ...]
...
Each sequence should be easily accessible by root numbers. Including specified "somedata"
Also the entire sequences of this structure should be easily transferred to the program memory, in the same form.
To be honest, I have no idea which solution is the best.
In the python it's a 3-dimensional list. It takes to much memory, so cannot be handled without periodic interaction with database.
Each row of a table can hold as much data as you like
You're working with softwaren not paper and pen, so your limitations should only be a concern when you actually find them
The point is to easily get the exact right data, What if string could reach over million symbols?
then I have to parse all that huge string in python just to discard most of this data?
Can anyone explain how to use the join command to connect tables with each other?
Looks like sqlite uses Hdd cache file for Execute operation, before to attach data to db file with Commit.
Is that so?
Is there any way to force it use ram memory instead?
Anybody know some SQLAlchemy? I'm trying to figure out the best way to return a list of a single column, e.g. ```py
session.query(MyModel.column).distinct().somehow_get_a_list()
Right now I get a nested list of tuples, no matter how I query. There must be some SQLAlchemy way to do this. ```py
(Pdb) session.query(Follow.follows).distinct().all()
[('volcyy',), ('vao92',)]
I've got this flatten-the-result-list pattern quite often here, so I'd be happy for any suggestions how it's possible to simplify this.
x[0] for x in y?
I think there is a proper way to do it in SQLA, but I'm not sure how it works
Yeah that's the short form of what I currently have, but I feel like there must be the right way™
https://pgexercises.com/ This is great
[SQLite3] What do you call it when you create a table and one var is numbers and karakters? Like c.execute("CREATE TABLE IF NOT EXISTS DiscordOffers(user TEXT, datestamp TEXT, id REAL, confirmed REAL)")
where user is like MK#7906
to my knowlege that's not a data type in sqlite
if you want to store users, it's probably better to store them by ID, since the ID cannot change while username / discriminator can
Yeah I thought of that too :p
@ionic pecan can you use an if else statement with c.execute? sorry to ask, but i am new to sqlite3 :p
not sure what you mean, can you show some code ?
I’ll do that in a bit, I’m currently on my phone xd
👍
@ionic pecan
id = ctx.message.author.id #discord thingie, so something like 2309328592385209
c.execute("SELECT * FROM DiscordUsers WHERE id=user")
for row in c.fethcall():
print(row)
how do you use an if and else statement here? Like if it has an outcome, that it will say like yes or something
like if there is one user with the given ID?
yeah
you probably want fetchone() instead of fetchall() https://docs.python.org/3.6/library/sqlite3.html#sqlite3.Cursor.fetchone
then you can do e.g.
c.execute("SELECT * FROM DiscordUsers WHERE id=user")
result = c.fetchone()
if result is not None:
# result is the queried user's row
else:
# result not found
also, I assume that the WHERE id=user is just a placeholder, but keep in mind that you should generally use parameter substitution
👍
I'm trying to use pymysql to add the values of a certain field up for 60k+ records, is there a faster way of doing this rather than going through all of the entries and adding the values up?
executemany should be used for bulk inserts https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-executemany.html
i'm doing a bulk select
So yes, you first have to make a list of tuples of all the stuff you wish to insert.
so just use executemany too?
What do you mean with a bulk select?
I have 60K+ records in a table currently, I need to get the value of a column from each individual record
okay so that's a normal select and you loop over the rows right?
yes
c.execute("SELECT * FROM DiscordOffers WHERE user=user") will always return the same
where user=user literally selects any DiscordOffer where user=user
completely independent of what's happening around it
you wanna pass the user into the execute
I think it's ```py
c.execute("SELECT * FROM DiscordOffers WHERE user=?", (user,))
but I could be wrong, you should re-check the docs to be sure
I am sorry, but I forgot what ? did and (user,))
I know user is a var
but what is the usage of it?
by using ? and passing (user,) as the second parameter, you're essentially putting the value of user into that WHERE user= statement
safely, that is
nope, was about to mention that
imagine this, you have an app where users submit comments
comment = await get_comment_from_user()
c.execute("INSERT INTO comments VALUES ({}, {})".format(user, comment))
okay now, this is bad, why? you're just inserting untrusted user stuff into your database
imagine comment was something like 'hello'); DROP TABLE comments;
then the SQL could be something like
INSERT INTO comments VALUES (
91032123, -- user id
'hello'); DROP TABLE comments;
)
do you see the issue? 😛
that's why you use ? for substituting parameters. you don't need to worry about that then
you can literally input code from the inside 'hacking' it
I think I saw that on yt too
where someone talked about that
yeah
basically, don't do that
super important
but yeah. now back to your question, now you should get the DiscordOffer corresponding to the user
no problem
hey guys,i was just wondering about what is the best database to use for my programming ? i use MySQL ,the workbench n all,but in youtube while browzing tutorials,u see people use various others which i dint know about..so just a little thought on this
@tawny sail are you going to have a million or more rows in your database?
not more than 40 or so
then it won't matter much to you
oh
SQLite would be fine for you
i did work on that,but i shifted to mysql later on lol
I don't see any reason to change it back if you already have something in place
small scale stuff isn't going to have a major impact unless you have been asked to evaluate efficiency or justify design choices
@ionic pecan sorry to disturb (again), but is this a REAL or a TEXT? <discord.message.Message object at 0x103a72130>
no not like that. I am trying to get a function that I can use client.delete_message(message_object)
and you cannot use the id
of the message
really?
lemme check this out
no, but the ID is known
it just needs to delete the message
it saves the message object in a database
and on request it deletes the message
like
if you do this
message_id = await client.say("test".format(ctx.message))
message_id_code = message_id.id
print(message_id)
print(message_id_code)
>>> <discord.message.Message object at 0x103a72130>
>>> 848948498895895898
You can't use message_id_code as a parameter in delete_message()
but if you want to do that youll have to store both channel ids and server ids i think..
lemme see
actually nvm
only channel id
so youll want both py message_object = await client.say("whatever") message_id = message_object.id message_channel_id = message_object.channel.id
message_id and message_channel_id
and then when you want to get that message object you can do py channel = client.get_channel(message_channel_id) message_object = await client.get_message(channel, message_id)
thanks
ill look at it :p
@torn sphinx when I try to store the ID in SQLite3, I get a number like 4.3953257433176474e+17
is REAL for floats?
REAL. The value is a floating point value, stored as an 8-byte IEEE floating point number.
yeah looks like
what is then the best to store it?
i dont know much about dbs, but maybe BIGINT
lemme try
or tbh you can store it as a string cuz ids are strings in the async version of discord.py
well, BIGINT worked 😄
ah ok
im not sure if itll be a str or an int when you retrieve it from the db, but make sure you pass strings whenever an id is required
if I retrieve it from the database it is this: ('359012789852831744', '2018-04-27', 439536454150914059)
so all good
ah ok so make sure you convert it to a string for the get_member and get_message stuff
isn't it to retrieve the id like this:
async def done(ctx):
try:
name = ctx.message.author.id
c.execute("SELECT * FROM DiscordOffers WHERE user =?", (name,))
for row in c.fetchall():
print(id)
conn.commit()
await client.say("{} I have succesfully closed your offer.".format(ctx.message.author.mention))
except:
raise
i used print to look if it works
frick
I get <built-in function id>
If i use row, I will get ('359012789852831744', '2018-04-27', 439536454150914059), what I don't, what I think. Since the ID is only relevant in this function
why that?
because thats an id right
for discord.py (async branch) the ids are strings
but on rewrite theyre ints
no problem but storing it as a string will just save you from casting it to a str
also you need both the message id and channel id to retrieve the message again
channel ID is always equal to the same channel
@torn sphinx just save it as TEXT you mean?
or
yes\
np
So I'm trying to make a mix of a database and a GUI, I will have songs and details about them. I am very new to python but I want to learn, this is a project I've been stuck on and I want some help, I have tried a few times, I can give those as examples, but they are very disorganized and sloppy as again I am inexperienced. I am 14 so if you can't handle the annoying voice you don't have to try to explain it. Thanks
hopefully you can teach me something further about classes and some basic concepts that I can't quite grasp from youtube videos
first of all ages isnt really important here, im 15 even the server owner is
if you are going for a databse plus GUI mix maybe take a look at sqlite and the sqlite3 module from the python standard library and for a farely simple GUI take a look at tkinter, from the standard library too
or do you have any specific questions
I've been attempting to use those two exactly
I'm just struggling apparently
its mostly some slightly more complex pieces of tkinter. It might not actually be complex, but it was difficult for me
@glass bough You may find this useful: http://appjar.info/
The easiest way to build tkinter GUIs in Python.
GUI library designed for people who are learning
Though this is off-topic for databases channel 😛
@glass bough Tkinter is fairly easy to understand, only getting the input from textboxes sucks ass
I couldn't get that working
lol
nearly everything from tkinter is what you expect every GUI framework to have in some form now days tbh
@broken linden bist du Deutsch?
indeed
trotzdem schreiben die Server Regeln aber Englisch vor ¯_(ツ)_/¯
I know, but just wanted to test you :0
I think I understand most of it, I just don't know how to make my code clear and to use some more advanced pieces to make it make more sense, using that appJar thing is like relearning it a bit
@broken linden deleting a row in SQLite3 is like c.execute("DELETE FROM DiscordOffers WHERE id=?", (name,)) right?
its like that in every sql dialect
@glass bough maybe try to learn the basics of Python
@broken linden I am having a problemos lol
😅
look
i mean
i am not sure about sqlite3 cause i never used it
but in my database projects i usually have
it causes some sort of 404 error
stuff like
I know a bit of python, but some of the things that people put in these chats confuse the hell out of me
def showID_to_name(ID):
app.config["CUR"].execute('SELECT title FROM "shows" WHERE id = %s',
(ID, ))
return app.config["CUR"].fetchall()
and yes
that new line is needed
is that MySQL?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NotFound: NOT FOUND (status code: 404): Unknown Message
wait maybe I know it xd
nope
scheisse
is the code you showed inside a cog or not?
(if you dont know what a cog is i am sure it isnt)
I choose the second option
lmao
but this is the right code
but it gives an error
#close offer
@client.command(description = "close an offer", pass_context = True)
@commands.has_any_role("Verified")
async def done(ctx):
try:
name = ctx.message.author.id
c.execute("SELECT id FROM DiscordOffers WHERE user =?", (name,))
for row in c.fetchall():
message_id = row[0]
channel = discord.utils.get(client.get_all_channels(), name="offers")
message_object = await client.get_message(channel, message_id)
await client.delete_message(message_object)
c.execute("DELETE * FROM DiscordOffers WHERE user=name")
conn.commit()
await client.say("{} I have succesfully closed your offer.".format(ctx.message.author.mention))
except:
await client.say("{} You do not have any open offers!".format(ctx.message.author.mention))
raise
it is that you use like !done
GOD DAMN IT
yeah
i think you gotta put the command decorator there
im not sure though
like
@client.command(pass_context=True)
async def test(ctx):
pass
already have that?
I think it is with the database, but not sure
is there some this exception was a direct cause of xyz thingy?
sometimes python spits out two exceptions
@broken linden no discrespect tho, meine liebe herr
that doesnt sound like correct german o_O
Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/discord/ext/commands/bot.py", line 846, in process_commands yield from command.invoke(ctx) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/discord/ext/commands/core.py", line 374, in invoke yield from injected(*ctx.args, **ctx.kwargs) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/discord/ext/commands/core.py", line 54, in wrapped raise CommandInvokeError(e) from e discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NotFound: NOT FOUND (status code: 404): Unknown Message
it means it didnt find the message
@broken linden could be true, cuz i am not a native xd
make sure the message isnt deleted
oh
@torn sphinx you are my savior in needs lmao
I love you so fucking much
YES
It worked
@torn sphinx ❤ ❤ ❤
btw
maybe handy for you
using channel = discord.utils.get(client.get_all_channels(), name="name of your channel") to get the channel is easier if the channel name is known
that works altho i think get_server is faster
esp if you have a lot of servers
or get_channel i mean
Well, using that sortof guiding tool (appJar) this has been incredibly simple
atleast for the basic parts of it that is
Those being being able to add to the table, now I just have to have a simple way to find specific details and pick out those songs
this is great:D
how can I fix the error No module named database ?
by installing a module named database, or making sure you are typing the right name
what the command to install database ?
I've never heard of it, but I'd imagine that you'd have to use pip install ... or python -m pip install ...
I will try
if you want to actually use a database module in python, I'd recommend starting with sqlite3 in the standard library
I'm creating a league of legends discord bot and wanting to store user data, what database do you guys recommend i use? (could potentially be on a LOT of servers)
i use sqlite for mine since i'm too lazy to set up something else
postgresql is fairly popular
its not necessarily going to be VAST amounts of data, just more speed of access i think
nods yupyup
But that's not an sql database
ive tinkered with rethink before
sod it, i'll give it a try
rethinkdb it is
thanks gdude
I think you'll like it
But remember, it has no access control
Don't expose the port
I am currently trying to get some simple database application to work, im running postgresql and created my main table with
CREATE TABLE "Users" (
"time" TIMESTAMP NOT NULL,
"count" INT NOT NULL,
"invite" VARCHAR(20) NOT NULL
);
however when my python code comes to the insertion point and tries to execute
INSERT INTO Users VALUES (1524907749.9109762,2392,'jQtfh66')
i get
psycopg2.ProgrammingError: relation "users" does not exist
creating the db with lowercase name fixed it
How can you create a column in a "main" table which includes the ID's of other tables?
@torn sphinx Having a little trouble 😅
link: https://pastebin.com/Ju8My7u1
I have marked where it is causing errors, could you look at what is wrong?
just search for !!!!!! problem is here !!!!!!
just one thing i noticed
put try: except: on the problematic line
not the whole thing
oh
or else you dont know where the error came from
but
whats the problem youre having?
i get multiple errors tbh
but it keeps changing
for instance
the error I get with this code is : Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/discord/ext/commands/bot.py", line 846, in process_commands yield from command.invoke(ctx) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/discord/ext/commands/core.py", line 374, in invoke yield from injected(*ctx.args, **ctx.kwargs) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/discord/ext/commands/core.py", line 54, in wrapped raise CommandInvokeError(e) from e discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnboundLocalError: local variable 'receiving' referenced before assignment
oh i see
you need to define receiving before you use it in the for loop
also this
for row in result_receiver:
receiving = row[0]``` lets say you do define receiving before you used it
itll change in each row
it searches for the AMOUNT tho?
but
just assign before the loop and reassign in the loop?
or
poke?
@torn sphinx sorry to ping
you can do like
receiving = None before the loop
but cant you just reverse the list and get the first item
how do you mean? sorry for the dumb question.....
so that code gets executed repeatably right?
ok i have a little more time now
so you want to keep repeatedly getting the first item in each row?
until it reaches the end?
isnt that the same as getting the first item in the reversed list
@torn sphinx I have fixed it 😅
ah ok
btw it might be better to ask more general questions in one of the help channels
and thanks 😅
oh
okay
btw
could I show you how I fixed it?
so you can see if I did it right or not
sure
the loop is kinda weird, you overwrite the variable every time
maybe you just wantto fetch the first result?
also, not entirely sure, does c.fetchall() ever return None?
or does it return an empty sequence when it doesn't get anything
what's that if result is None check then?
maybe you want if not result to check if the result is empty?
okay, this is a kind of mixed chat question, if I take something from a database and want to print it as a label on a GUI, say all the parts of a row in a table, how would I do this? I am using tkinter and sqlite3
@ionic pecan yeah forgot that :c
someone know where can I find my token from MongoDB ?
Token..?
MongoDB doesn't use authentication by default
To set that up, you have to explicitly set the passwords
So there's nowhere to "get" the "token"
You're expected to not lose the password
Maybe he means his discord token
He said that wasn't it in another channel
Oh welp
need some help with my mongodb program. It's using flask-pymongo(basically flask). This is probably the easiest question, but googled for like 25 min and haven't found anything that really makes sense. Basically I'm trying to search through the users collection, and query/find a document that has a certain email field and grab the documents string that has the api key in it and set it to a variable. Anyone know how I would do this?
Wait so you have a document
What is the form of that document? Does it contain both email and api key? @small dirge
yes @viral crag
yeah, so you just get the document by the email address
and you'll get the whole document
including the api key
How could I set a limitation so I am unable to add something that is already in any of the columns in a database
to prevent duplicates
@glass bough you would have to querry the DB for the results and check to see if it's already there
Ok, I have another problem
I used and coppied code that insarting data into SQL base
I added my query and edited args, but nothing else
File "C:\Python35\lib\site-packages\discord\client.py", line 307, in _run_event
yield from getattr(self, event)(*args, **kwargs)
File "C:\Users\saaswww\Desktop\bonkobot\bot.py", line 112, in on_message
rules_confirm(message.author.id)
File "C:\Users\saaswww\Desktop\bonkobot\bot.py", line 63, in rules_confirm
cursor.close()
UnboundLocalError: local variable 'cursor' referenced before assignment```
you're using cursor before you assign it
I now it
But i defined it
query = "INSERT INTO users(Discord_ID,rules) " \
"VALUES(%s,%s)"
args = (Discord_ID, 1)
try:
db_config = read_db_config()
conn = MySQLConnection(**db_config)
cursor = conn.cursor()
cursor.execute(query, args)
if cursor.lastrowid:
print('last insert id', cursor.lastrowid)
else:
print('last insert id not found')
conn.commit()
except Error as error:
print(error)
finally:
cursor.close()
conn.close()```
How to make it global?
in rules_confirm() ?
Yeah
yyyyy
try:
dbconfig = read_db_config()
conn = MySQLConnection(**dbconfig)
cursor = conn.cursor()
cursor.execute("SELECT rules FROM users WHERE Discord_ID= `%s`")
args=(DiscordID)
row = cursor.fetchone()
while row is not None:
print(row)
row = cursor.fetchone()
except Error as e:
print(e)
finally:
cursor.close()
conn.close()
def rules_confirm(Discord_ID):
conn = ""
cursor = ""
query = "INSERT INTO users(Discord_ID,rules) " \
"VALUES(%s,%s)"
args = (Discord_ID, 1)
try:
cursor = conn.cursor()
db_config = read_db_config()
cursor.execute(query, args)
conn = MySQLConnection(**db_config)
if cursor.lastrowid:
print('last insert id', cursor.lastrowid)
else:
print('last insert id not found')
conn.commit()
except Error as error:
print(error)
finally:
cursor.close()
conn.close()```
I tryied to fix it by defining empty vartibiles, but:
File "C:\Python35\lib\site-packages\discord\client.py", line 307, in _run_event
yield from getattr(self, event)(*args, **kwargs)
File "C:\Users\saaswww\Desktop\bonkobot\bot.py", line 112, in on_message
rules_confirm(message.author.id)
File "C:\Users\saaswww\Desktop\bonkobot\bot.py", line 63, in rules_confirm
cursor.close()
AttributeError: 'str' object has no attribute 'close'```
well now you're defining cursor as a string
same thing for conn
you've messed up your line ordering
look at your try block
first line, get a cusor from the connection
second line, get the db config
third line, execute a query on the cursor
fourth line, create a connection using the db config
that's what you're doing, and yeah that definitely won't work
you need to define your db config, connection and cursor at the top of that function, in that order
db_config = read_db_config()
conn = MySQLConnection(**db_config)
cursor = conn.cursor()
query = "INSERT INTO users(Discord_ID,rules) " \
"VALUES(%s,%s)"
args = (Discord_ID, 1)
try:
cursor.execute(query, args)
if cursor.lastrowid:
print('last insert id', cursor.lastrowid)
else:
print('last insert id not found')
conn.commit()
except Error as error:
print(error)
finally:
cursor.close()
conn.close()```
Now NameError: name 'read_db_config' is not defined
Well, then I guess you didn't define it
Okay so this is more SQL than Python, but my web server is throwing me an operational error which doesn't happen elsewhere. This is the code:
params3 = ("TRUE", discord_date_to_unix(datetime.utcnow()), "FALSE", discord_id)
udb.execute("UPDATE UserMainTable "
"SET (IsRegistered, RegisterDate, SendRegistrationReminders) "
"= (?,?,?) "
"WHERE DiscordID is ?", params3)```
And here's the error:
File "/dobby3/DobbyCommands.py", line 369, in register_user_account_in_db
if int(res2[0]) == 0:
params3 = ("TRUE", discord_date_to_unix(datetime.utcnow()), "FALSE", discord_id)
udb.execute("UPDATE UserMainTable "
"SET (IsRegistered, RegisterDate, SendRegistrationReminders) "
"= (?,?,?) "
"WHERE DiscordID is ?", params3)
sqlite3.OperationalError: near "(": syntax error```
Hold up, messed up the formatting
There ya go
what SQL dialect is this?
SQLite 3
I think it's SET VALUES, not just SET
I had some issues getting it to work actually
Had to install the dev package and recompile Python
I'll give it a go, thanks
@viral crag Now it's the same error, except that it's displaying near "VALUES"
I wonder if it's the brackets actually
Is is a thing in SQL?
It's a bit further there, but I recall always using = for this
oh, it'd be LIKE I think
I'm not sure honsetly, the error you have is an SQL syntax error though
https://sqlite.org/lang_update.html I'm checking here but I don't see anything wrong
I found it. For whatever reason the SQLite version is a right stickler when it comes to formatting
I can't use SET c1, c2, c3 = ?,?,?
Instead I have to use
SET c1 = ?, c2 = ?, c3 = ?
On my desktop/laptop it works fine though
Hmm
It might be to do with the issue I had with it before
@ionic pecan I am using slite3 I assume that applies to normal SQL, but I'm very inexperienced with some of this stuff
https://www.w3schools.com/sql/sql_constraints.asp you should check these out
the pages after it explain more about it
it's still sortof confusing
because I don't know where I would put that in my code
well I just made it so that when I add something, it takes the name input and deletes the rows with that name and then adds the new one
Does this make sense to do?
Or is there a better method
Well, I figured it out in a better way
so I ended with the constraint of INSERT OR IGNORE
but instead of ignoring, is there a chance I can have it tell me when something is repeated
I think you can use ON CONFLICT
also that's not a constraint
a constraint would be something like name VARCHAR(30) UNIQUE
you need to put these constraints to your table creation
I put unique in the table part with my insert and ignore in the main body
select from table a row where username == variable can someone translate this to proper postgresql
SELECT *
FROM table_name
where username = variable;
I have a MySQL database running and I'm using the mysql.connector.
I need to insert millions of rows into a table, what is most efficient (fastest) way to do so?
I've tried just
sql = "INSERT INTO users VALUES (%s, %s, %s, %s)"
cursor.execute(sql, (data[0], data[1], data[2], data[3]))
But for one million inserts it takes 30-40 minutes
https://stackoverflow.com/questions/6159087/mysql-is-taking-too-long-to-insert-rows
https://dba.stackexchange.com/questions/61029/inserting-60-000-rows-taking-too-long
@barren swallow do either of these help? Basically.. how are you inserting each row? does each one have an insert into statement?
I have one page where users can import their contacts. Initially it was working fine upto 3000 contacts but when I tried to import 10000 contacts it started taking too much time and now the situati...
I'm currently testing out executemany function
but loading 15 million rows into memory isn't ideal so I will need to code it to do 1K at a time or something like that
From where are you getting the rows?
If it's a large file, you can use mmap to slowly traverse it instead of reading all of it by once https://docs.python.org/3/library/mmap.html#module-mmap
ATM I'm using
with open('x.txt', encoding="utf8") as f:
for row in f:
Apparently it just loads it row by row
what is in the text file? comma seperated rows?
Something like that, yes
Hmm
ok if you want something fast and easy convert the text file into a csv and do LOAD DATA FROM INFILE '<filepath>/x.csv' INTO TABLE users
hmm
otherwise, you want to group rows and do the insert as batches
because the executemany is doing an insert every time which is slow
So for importing large quantities of rows import is always a better choice?
as far as i know yes, as long as you don't need to manipulate the data inbetween
Hi
Well, I actually need.
ok in that case, what you need to do if you want speed is to create an insert statement that inserts lots of rows at once. your executemany statement is adding overhead to every single row you are adding
I should parse the file using Python and create a csv file and import the csv file?
that could work
Hey guys, a bit confused
Using mongodb, should I be creating a new collection for every user?
atm i've been creating new documents for each user
it depends on what all you're storing
well...
no it should pretty much just be documents
what makes you think you'd need individual collections?
not sure, i just have to store a lot of data
it would be a lot of fields for each user
@vestal apex
well you can break user info across multiple collections, but sometimes you just have lots of fields
if you've got a considerable number of fields that would work well in, say, a table
you might want to consider a relational database
my project is just starting though, and i want to be able to change and work with things very easily which is why I chose mongodb
i don't want to be forced to use a structure right away
I was having problems with importing large quantities of data into a MySQL database earlier.
I found the solution, mysqlimport.exe is the best solution. With it I was able to import 100k rows in less than a second
lol that sounds like an ad and half
Question regarding foreign keys.
CREATE TABLE mute (
expiry DATETIME,
active BOOLEAN,
infraction_id INTEGER NOT NULL,
PRIMARY KEY (infraction_id),
CHECK (active IN (0, 1)),
FOREIGN KEY(infraction_id) REFERENCES infraction (id) ON DELETE CASCADE
);
This is my schema. When I delete the referenced infraction, the mute doesn't seem to delete. My understanding is that ON DELETE CASCADE would also delete the mute, but it doesn't. What would I use instead?
Maybe this is an issue with how I execute the delete. Using SQLAlchemy:
query = infraction_db.delete().where(and_(
infraction_db.c.id == id_,
infraction_db.c.guild_id == ctx.guild.id
))
result = await self.bot.db.execute(query)
@ionic pecan have you fixed this?
Yes
Turns out SQLite doesn't support Foreign Keys without enabling it
so that just failed silently, which annoyed me a slight bit, so I use pgsql now
thanks though
depends on what scenario you've got and what you plan to do @orchid charm
I just want a Profile system
Where i can write stuff in a Specific Cagetories so the bot can grab the info
Like if i typed !profile add weapon splattershot It would write to a Weapons Cagetory Splattershot
@gusty spindle Also what do you mean by Scenario
Do you mean what i am gonna use?
If so i have no idea whatsoever
i'm not too sure about DB's, but i know some are better at smaller-scale projects and others are better at much larger-scale things
I just want a profile system like this
The Bot is not in Github so i can't look at what the Person who devved this bot did with it
What's the correct datatype for storing strings converted to bytes in postgres?
reason = Padding.pad(bytes(reason, "utf-8"), 16)
enc_msg = self.aes.encrypt(reason)``` kinda message
What do i do if i wanted a Sqlite3 discord bot to check if something exists in a db and do something if it does not exist in the db
Like i got 3 Columns, UID, IGN, WEAPON
How would i make the bot check UID for a Specific value in UID
Cool
👍
So like this?
c.execute('SELECT UID from Profile where name = ?', (name,))
Cause bot.run is not working
I am currently working on it
It worked this time, so time to see if that thing works
It gives me a error
"name" is not defined
@gusty spindle Do you know what i am doing incorrectly?
Wait think i fixed it
hmm
@gusty spindle Yo do you know what everything in that thing means
I want it to look for the Author of the messages ID in Table Profile Column UID
are you using postgresql ?
No, SQlite3
For a discord bot?
Yeah
Hmm, haven't used sqlite. Most say postgresql works best with discord bots using asyncpg
I am using asyncio
That's what asyncpg is, an async api for postgres
sqlite3 is good for beginners ^^
Anyways, am i having it search correctly
c.execute('SELECT UID from Profile where UID = ?', (ctx.message.author.id,))
rows = c.fetchall()
if (ctx.message.author.id,) not in rows:
print('Profile Created!')
else:
print(ctx.message.author.name + ' You already have a Profile!')
I just want it to see if the Message authors ID is in Table Profile Column UID
And if it does it does something, and if it does not it does something else
you just need to do if ctx.message.author.id not in rows i think
oh wait i don't know
Isn't rows a list of rows
Not Ids
As in you have to loop through the rows and check the id column for each row?
c.execute('SELECT UID from Profile where UID = ?', (ctx.message.author.id,))
rows = c.fetchall()
for row in rows:
if ctx.message.author.id != row["UID"]:
print("Profile Created!")
else:
print("Already exists")```
Try looping over the rows
Actually, you're already checking if the id exists in your query.
Just check if rows is None or not
fetchall()
Fetches all (remaining) rows of a query result, returning a list. Note that the cursor’s arraysize attribute can affect the performance of this operation. An empty list is returned when no rows are available.
How will you check if the id is in the database if you don't query it?
¯_(ツ)_/¯
c.execute('SELECT UID from Profile where UID = ?', (ctx.message.author.id,))
rows = c.fetchall()
if not rows:
print("Profile Created!")
else:
print("Already exists")```
So i use that?
Well, like the method documentation says. It returns an empty list if theres no rows from the query. Your query is asking for a row with a specific ID, which I assume is a primary or atleast unique Key in your database
So if it finds a result, you'll only get 1 row, else an empty list. If it's empty you don't have any rows in your db with that Id, hence it doesn't exist
Well the thing you gave me worked
👍
I put my User ID into my Database and tested it
And you understand why?
Mhm, pretty sure i get it

How do i use a database in another folder
Sqlite 3
so sqlite3.connect
But i do the directory it is in instead of name?
Ah
Thought so
How do i grab DB info and post it in chat with the bot
How do i grab it
Example of doing that
@modest haven Well what if there are multiple of the same thing
Cause there is gonna be stuff like Weapon in there which multiple will be the same
Yeah
That is what i was saying
How exactly do i do that
🤔
@modest haven
Also wow took me like 10 seconds for the ping to send 🤔
@modest haven
That is what a Default DB looks like
For what i am gonna be doing
So it would need to find the Line with the matching UID then grab from that line IGN, and Weapon then set it to some variable
@modest haven So like this?
bot.c.execute('SELECT Weapon from Profile where UID = ?', (ctx.message.author.id))
Also what am i doing wrong with this
self.bot.c.execute('SELECT Weapon from Profile where UID = ?', (ctx.message.author.id))
I just want it to grab the line with your username and take from that line weapons
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/ext/commands/core.py", line 62, in wrapped
ret = yield from coro(*args, **kwargs)
File "/Users/shanehawkins/Desktop/DiscordBot/cogs/member.py", line 30, in profile
self.bot.c.execute('SELECT Weapon from Profile where UID = ?', (ctx.message.author.id))
ValueError: parameters are of unsupported type
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/ext/commands/bot.py", line 886, in invoke
yield from ctx.command.invoke(ctx)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/ext/commands/core.py", line 514, in invoke
yield from injected(*ctx.args, **ctx.kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/ext/commands/core.py", line 71, in wrapped
raise CommandInvokeError(e) from e
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: parameters are of unsupported type
That is the Error when i use the command that it is linked to
@commands.command()
async def profile(self, ctx):
self.bot.c.execute('SELECT Weapon from Profile where UID = ?', (ctx.message.author.id))
Weapon = self.bot.c.fetchone
WeaponID = Weapon[0]
await ctx.send('Favorite Weapon {}'.format(Weapon[0]))
This is the command
i believe that you need to pass it an iterable of parameters
right now you pass it a single one
How do i do that Exactly
you need to add a comma at the end of ctx.message.author.id to make it a tuple, e.g. (ctx.message.author.id,)
that's my guess, the traceback is not entirely obvious
Why do i keep forgetting to do that

Ok new error
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/ext/commands/core.py", line 62, in wrapped
ret = yield from coro(*args, **kwargs)
File "/Users/shanehawkins/Desktop/DiscordBot/cogs/member.py", line 32, in profile
WeaponID = Weapon[0]
TypeError: 'builtin_function_or_method' object is not subscriptable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/ext/commands/bot.py", line 886, in invoke
yield from ctx.command.invoke(ctx)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/ext/commands/core.py", line 514, in invoke
yield from injected(*ctx.args, **ctx.kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/ext/commands/core.py", line 71, in wrapped
raise CommandInvokeError(e) from e
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'builtin_function_or_method' object is not subscriptable
@commands.command()
async def profile(self, ctx):
self.bot.c.execute('SELECT Weapon from Profile where UID = ?', (ctx.message.author.id,))
Weapon = self.bot.c.fetchone
WeaponID = Weapon[0]
await ctx.send('Favorite Weapon {}'.format(Weapon[0]))
That is what i get from the command now when i use it
The goal of this command is to Grab from the line that has your User ID in it whatever Weapons is
fetchone is a method, not an attribute
So what do i do to fix
you call it
this should give you an idea ```py
def add(a: int, b: int):
... return a + b
...
add
<function add at 0x10cb7af28>
add(2, 3)
5
fetchone is a method on the cursor
nowhere
Basically, what you're doing is WeaponID = self.bot.c.fetchone[0]
and fetchone is a method
you want to access index 0 on the result of fetchone, not the function itself
O
@commands.command()
async def profile(self, ctx):
self.bot.c.execute('SELECT Weapon from Profile where UID = ?', (ctx.message.author.id,))
self.bot.c.fetchone
await ctx.send('Favorite Weapon {}'.format())
@ionic pecan How do i access Index 0 then
Brain.exe has stopped working, its like 11:00PM PT
i think you want WeaponID = self.bot.c.fetchone()[0]
so that calls fetchone, and then you access it with the [0]
just so you know what its doing
Now all i gotta do is figure out how to write like that
So i can write to the Weapon Cagetory that has the UID with my user id in it
is it an insert or an update you want to do
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
thats the general syntax
i will let you figure it out
let me know if you need help
New error
I manually wrote to the Weapon Column Splattershot pro
Now if i use the command i get this
Ignoring exception in command profile:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/ext/commands/core.py", line 62, in wrapped
ret = yield from coro(*args, **kwargs)
File "/Users/shanehawkins/Desktop/DiscordBot/cogs/member.py", line 31, in profile
WeaponID = self.bot.c.fetchone()[0]
TypeError: 'NoneType' object is not subscriptable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/ext/commands/bot.py", line 886, in invoke
yield from ctx.command.invoke(ctx)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/ext/commands/core.py", line 514, in invoke
yield from injected(*ctx.args, **ctx.kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/ext/commands/core.py", line 71, in wrapped
raise CommandInvokeError(e) from e
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'NoneType' object is not subscriptable
@commands.command()
async def profile(self, ctx):
self.bot.c.execute('SELECT Weapon from Profile where UID = ?', (ctx.message.author.id,))
WeaponID = self.bot.c.fetchone()[0]
await ctx.send('Favorite Weapon {}'.format(WeaponID))
fetchone returns None
probably because it didn't find anything with the query
and you try to access None at index 0
result = self.bot.c.fetchone()
if(result != None):
WeaponID = result [0]
else:
#error case here
@orchid charm bit of error checking
So where do i put that
delete WeaponID = self.bot.c.fetchone()[0] and put that instead
im not sure what your error case is because idk what your program does
can just have it printing something for debug purposes
if you can't think of anyting put print("Error fetching weapon id result") or something
this Cog is for a Profile system
The user Writes information to the DB
Then when they type !profile the bot displays it in a embed
But for now no embeds
ok so in the case there is no weapon id result (database doesn't have one) what do you want it to do?
send a message? leave something blank?
that is what the error case is for
you want it to say that in the database?
ok so where i put #error case here put a sql update statement
self.bot.c.execute("UPDATE Profile SET Weapon='Weapon Unset' WHERE UID=?", (ctx.message.author.id,))
@orchid charm give that a go
@commands.command()
async def profile(self, ctx):
self.bot.c.execute('SELECT Weapon from Profile where UID = ?', (ctx.message.author.id,))
result = self.bot.c.fetchone()
if(result != None):
WeaponID = result [0]
else:
self.bot.c.execute("UPDATE Profile SET Weapon='Weapon Unset' WHERE UID=?", (ctx.message.author.id,))
await ctx.send('Favorite Weapon {}'.format(WeaponID))
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/ext/commands/core.py", line 62, in wrapped
ret = yield from coro(*args, **kwargs)
File "/Users/shanehawkins/Desktop/DiscordBot/cogs/member.py", line 36, in profile
await ctx.send('Favorite Weapon {}'.format(WeaponID))
UnboundLocalError: local variable 'WeaponID' referenced before assignment
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/ext/commands/bot.py", line 886, in invoke
yield from ctx.command.invoke(ctx)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/ext/commands/core.py", line 514, in invoke
yield from injected(*ctx.args, **ctx.kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/ext/commands/core.py", line 71, in wrapped
raise CommandInvokeError(e) from e
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnboundLocalError: local variable 'WeaponID' referenced before assignment
@runic tundra
add WeaponID='Weapon Unset' just above the the sql select statement
Which one, the else statement? @runic tundra
Ok did it
Now time to try it when i set the Weapon Value
? @runic tundra
what don't you understand
you asked where to put it i said above the select statement
Ah
@commands.command()
async def profile(self, ctx):
WeaponID='Weapon Unset'
self.bot.c.execute('SELECT Weapon from Profile where UID = ?', (ctx.message.author.id,))
result = self.bot.c.fetchone()
if(result != None):
WeaponID = result [0]
else:
self.bot.c.execute("UPDATE Profile SET Weapon='Weapon Unset' WHERE UID=?", (ctx.message.author.id,))
await ctx.send('Favorite Weapon {}'.format(WeaponID))
But the thing is i set the DB
wait
urr ok so you need to do some debugging
give me a sec
@commands.command()
async def profile(self, ctx):
WeaponID='Weapon Unset'
self.bot.c.execute('SELECT Weapon from Profile where UID = ?', (ctx.message.author.id,))
result = self.bot.c.fetchone()
if(result != None):
WeaponID = result[0]
else:
await ctx.send('UID from discord {}'.format(ctx.message.author.id))
self.bot.c.execute("UPDATE Profile SET Weapon='Weapon Unset' WHERE UID=?", (ctx.message.author.id,))
await ctx.send('Favorite Weapon {}'.format(WeaponID))
@orchid charm try that and see what it sends
if the userid matches the one in the database
the user ids are correct but the select is retuning None
i gotta go do stuff so i cant help right now hopefully someone else can help
Also when Weapon is Null it says None
Ok well it actually worked this time
I reset my DB to default and it functioned Properly
Ok, new Question
How do i set Names value to argument
It is Currently Null
So how do i set it to a Argument
@orchid charm that should be very easy to find in a google search or on the sqlite3 docs
What would i even search, How to Update Table Column where something exists?
self.bot.c.execute("UPDATE Profile SET FC=? WHERE UID=?", (arg1, arg2, arg3, ctx.message.author.id,))
How do i make it SET FC= to Arg1, Arg2, and Arg3
That doesnt make sense
Ok just did a Different method
?
Yea, thatll work
FC1 is set to Arg1, FC2 is set to Arg 2, ect.
How do i make it require it to be numbers
And how do i make it require each arg to be 4 Characters long
Youd do that with python
@bot.event
async def on_message():
self.bot.c.execute('UPDATE Profile SET XP=XP+5 WHERE UID=?', (ctx.message.author.id,))
self.bot.conn.commit()
Ignoring exception in on_message
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/client.py", line 224, in _run_event
yield from coro(*args, **kwargs)
TypeError: on_message() takes 0 positional arguments but 1 was given
What am i doing wrong
what do you think you are doing?
on_message() takes no arguments and apparently on line 224 of client.py you called it with an argument
you forgot to do on_message(self):
Ohhh
This was a Database question too so i put it in here just incase it had to do with my DB, also incase i do something wrong with my DB
@bot.event
async def on_message(message):
async with aiosqlite.connect('profiles.db') as db:
await db.execute('UPDATE PROFILE SET XP=XP+5 where UID = {}'.format(message.author.id))
What exactly am i doing wrong, it is not adding 5 to XP
XP by default is 0
Also using aiosqlite now
NVM, i forgot to commit
Ok, now i need to figure out how to make the bot check if the users XP is 100, and if it is add 1 to level
Or to be more clear, whenever the users xp is a multiple of 100 it adds one level
So i become LV 1 at 100 EXP, 2 at 200 EXP ect.
just make their level equal to their EXP // 100
Oh?
can you not use google?
¯_(ツ)_/¯
"python number has multiple" should give you a result
@bot.event
async def on_message(message):
bot.db = await aiosqlite.connect('profiles.db')
await bot.db.execute('UPDATE PROFILE SET XP=XP+5 where UID = {}'.format(message.author.id))
await bot.db.commit()
await bot.db.execute('SELECT XP from Profile where UID = ?', (message.author.id,))
result = bot.db.fetchone()
if (result x%100==0):
await bot.send('You levelled up!')
@gusty spindle So like that?
i suppose, yup ^^
@bot.event
async def on_message(message):
bot.db = await aiosqlite.connect('profiles.db')
await bot.db.execute('UPDATE PROFILE SET XP=XP+5 where UID = {}'.format(message.author.id))
await bot.db.commit()
await bot.db.execute('SELECT XP from Profile where UID = ?', (message.author.id,))
result = bot.db.fetchone()
if (result == x%100==0):
await bot.send('You levelled up!')
Ignoring exception in on_message
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/client.py", line 224, in _run_event
yield from coro(*args, **kwargs)
File "./main.py", line 37, in on_message
bot.db = await aiosqlite.connect('profiles.db')
TypeError: object Connection can't be used in 'await' expression
@gusty spindle That is what happens now
It worked before i added result
i have no idea how to use aiosqlite but try removing the await
I am gonna migrate to PostgreSQL
@gusty spindle
@bot.event
async def on_message(message):
await db.execute('UPDATE PROFILE SET XP=XP+5 where UID = {}'.format(message.author.id))
await db.commit()
await db.execute('SELECT XP from Profile where UID = ?', (message.author.id,))
row = await bot.db.fetchone()
if (row == x%100==0):
await bot.send('You levelled up!')
File "./main.py", line 43
if (row == x%100==0):
^
IndentationError: unindent does not match any outer indentation level
What is wrong
Or wait, i think i know
Nvm
@gusty spindle Oh yeah i got this error
https://hastebin.com/dabahelevi.sql
What does it mean exactly
i have no idea how to use postgresql databases, sorry
Oof
What databases do you know how to use then XD
Well if anyone knows what this means and how to fix ping me
https://hastebin.com/dabahelevi.sql
@orchid charm Something wrong with your credentials object
Make sure that's the correct way to do what you're doing by reading the docs
credentials = {
"user": "(Not Showing You)",
"password": "(Not Showing You)",
"database": "profiles.db",
"host:": "127.0.0.1",
}
@viral crag
Those are my Credentials
So are you supposed to pass a dict into that function?
?
I would have expected a connection url
a connection url?
A connection url.
How do i get one
You make one
How XD
It'll be something like uhh
"aiopg://username:password@host:port/database"
Something like that
O
Unless you just meant to unpack that dict
I just wanted that dict to be my credentials
In which case you needed **credentials
In the function call
Basically that unpacks the dict into keyword arguments for the function
Ohh
TypeError: connect() got an unexpected keyword argument 'host:'
@viral crag So i just remove host?
Ok, it worked
but password authentication failed
No, don't remove host, remove the colon in the host key
o
Alright well, wrong username and password :P
You'll have to look that up
I don't know the reset process and I'm going to bed anyway
by the way you seem to be asking a lot of questions which you can answer with google.
postgres is dead simple to set up on mac
probably the easiest of all the OSs
@lyric stag Also, sqlite3 was easier to install 👍
Also i ran Nadekos before this so i already was running sqlite
check out that link I posted, it's really easy
Hopefully it works this time, i might have to uninstall alot of stuff cause of it conflicting with everything
Also wow i am suprised anyone is up rn
Its Midnight (in PT)
i'm moving out of my uni for the summer
aight i'm getting started on mongodb cuz i need that json like shit
yea lol someone told me about it in this server
I think it's perfect for what I'm using
Json would be for a smaller bot
but I'm completely new to databases
Sqlite would work better probably
^
rethinkdb?
Also, you're wrong @orchid charm
lmao
Nom
oof
Sqlite best DB ever confirmed 2018
JSON files are no good for larger applications, yes
These things are far from JSON files
Don't you need to apply everything at once to a json file?