#databases
1 messages · Page 48 of 1
to store them all in a variable like inventory for iteration, a bit of querying would be needed
Alright ty
Has anyone ever used YAML to automate Google Sheets?
guys what would be a efficent way to query a big db 100k + records
i will have a searchbar query that db and fipter the output
filter
it contains video so im gonna look for terms on the table. 2 cols will bd used in the search
which database are you using?
to tell the truth i kind of have no idea
didn't change any config
its a mysql db , not sure about the engine its using
ive been thinking of limiting a query to 10k , grab the records do fuzzy search on it and if x records are not found , repeat with next 10K
that would speed things a bit i think
You have SQL for a reason
As long as your query is not awful, and you have setup proper indexes, leave the DB to do all that stuff for you
well the server IO performance is bad since its on my laptop
well the server IO performance is bad since its on my laptop
@torn sphinx use commas or a separate table with inserts of items. I use SQLite and in my discord program i have a item table for a collectable I call banners
This is how it grabs the information
cur.execute(“SELECT * FROM * WHERE ID = (SomeId)”)
ItemList = cur.fetchall
If you want to use a comma way do this
cur.execute(f”UPDATE * SET * = *{newitem} WHERE * = *”)
Then just do a fetchone and re the output to get the items which are in between the ,
These both should work
and btw cur is your connection cursor
I would use the comma way due to it being way more efficient
A item table is easier but would use more data
DON'T use f-strings for parameter substitution
bad, bad, bad, bad, bad
if newitem happens to be something like ```sql
'hi';
SELECT
'DROP TABLE ' || name || ';'
FROM
sqlite_master
WHERE
type = 'table'; --
I use keys
Is that good?
c.execute("INSERT INTO users VALUES (:name, :id, :xp)", {'name': ctx.message.author.display_name, 'id': ctx.message.author.id, 'xp': 0})```
@orchid charm ty
keys are fine, that's using execute's substitution mechanism
even if you're not taking user input, you should never ever use unclean string substitution
better to be in the habit of doing it the right way every time
guys is it possible to insert string date directly as date format on a mysql db?
@hazy crystal probably, it might have to be in a particular format
According to https://dev.mysql.com/doc/refman/8.0/en/date-and-time-literals.html, it should be in yyyy-mm-dd hh:mm:ss format.
@patent glen what if its yyyy-mm-dd (without h) and send from a python script as a string?
@hazy crystal yyyy-mm-dd should be fine for date, i was looking at datetime
anyway try it and see
works for me with mysql.connector
i guess i should try it , btw do you know js by chance? I need to read a jquery script to find out how its working 😄
i know basic js but don't have a clue about jquery
ok its fine gonna figure it out with trial and error :D. btw i tried inserting it in the right format and it works.
You might find js channels in #315249263103967242
This might be a really basic database question, but how would you suggest working with a connection across multiple modules.
or is this more suited to one of the help channels?
depending on your use case, you could either: pass in the connection (or cursor) to whatever function needs it, maintain the connection (and/or cursor) in a single module and have every other module import that module, or just keep opening and closing connections instead of having a single connection object (sqlite connections are cheap, and i think most other db modules implement a connection pool)
some of these solutions may not be suitable for multithreaded usage.
I currently have a helper class, so that I don't litter the code up with a bunch of the same queries
that could be changed to open and close a connection each time one of it's function is called
or I could make it a singleton(the pythonicish way)
Which seems better or does it ultimately not matter?
well you could make the connection an attribute on the class instance
make sure to add a close method, and maybe also a context manager, if you go that route
I only use f strings if it can’t be something dangerous
@orchid charm well, don't
im trying to add columns in a loop in sqlite3 without using string concatenation due to the risk of SQL injection. i found this answer on stack exchange https://stackoverflow.com/questions/30824392/add-columns-to-an-sqlite-table-in-a-python-loop however i get a syntax error as follows
cursor.execute("ALTER TABLE data ADD COLUMN ? INTEGER", ("test",))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
sqlite3.OperationalError: near "?": syntax error
any ideas as to what im doing wrong? (using python3 if that means anything) edit: please ping me in your response
@charred marsh You cant use parameters for table/column names
In this instance, you have to use string formatting
hmm ok, i wonder why it worked on stackexchange then 😕
If you mean his answer, I doubt he tested it
Hello any fast way to transfer a json database into SQLite? I would do it buy copy pasting but.... Theres 1.200 people in my database and each of them have like 8 colums so rip lol
no idea what a "json database" is, but if it's a json file, then just do it through python, you may want to look into the json module aaaaand
bot.docs['sqlite3.Cursor.executemany']
executemany(sql, seq_of_parameters)```Executes an SQL command against all parameter sequences or mappings found in the sequence *seq\_of\_parameters*. The [`sqlite3`](#module-sqlite3 "sqlite3: A DB-API 2.0 implementation using SQLite 3.x.") module also allows using an [iterator](../glossary.html#term-iterator) yielding parameters instead of a sequence.
```py
import sqlite3
class IterChars:
def __init__(self):
self.count = ord('a')
def __iter__(self):
return self
def __next__(self):
if self.count > ord('z'):
raise StopIteration
self.count += 1
return (chr(self.count - 1),) # this is a 1-tuple
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table characters(c)")
theIter = IterChars()
cur.executemany("insert into characters(c) values (?)", theIter)
cur.execute("select c from characters")
print(cur.fetchall())
``` Here’s a shorter example using a [generator](../glossary.html#term-generator):
```py
import sqlite3
import string... [read more](https://docs.python.org/3.7/library/sqlite3.html#sqlite3.Cursor.executemany)
you need to go from json dictionary to values, and then make that into a list of tuples
ok ty
Hello. If I want to get access to for example "level"
I have to do py data[3]
Why I can't Just use py data["level"] :/
is that... excel?
anyways, if you're using the built-in sqlite3 module, i think you're stuck with that since it returns a list of tuples
What?
@ionic pecan Thats a DB Browser for Sqlite
@ornate abyss ?
Whats the diffrerence if I do
data["level"]
or
data[3]
Its the same lol
Im looking ELK channels, to dicuss elasticsearch nosql etc
NoSQL would still fit in here @mild orbit
apologies in advance for asking the simplest questions, but which way of storing data is a good start? i'm trying to program a small discord bot that stores user input data from my friends for a small game.. should I create one list/array for each user and store the list in a .csv or .txt file?
or is there better options? do you have any good learning material from the internet?
most of the people use json files for simple data in discord bots
json sounds rather advanced or am i wrong? wouldn't a .txt or .csv file be enough?
i'm a beginner beginner by the way
and you have a builtin json module
sqlite3 is a fairly easy Python module. Requires a little knowledge of SQL though.
👌🏻
@quaint swallow Json is not too hard
You basically just treat it as a python dict, then use the json module to save and load the json file
yeah if you can use lists and dicts, youre pretty much set with json. its not that difficult
@quaint swallow json's have worked a charm for me
One thing i would say is keep all the funcs that read and write to it in one file
Something like storage.py
That way, if you move to a database, its easier to move over than having the code all over the place ;D
Is it a bad idea to keep a connection to a database open for the entire runtime of an application? Is this something that prevents others from accessing the database?
I have been using sqlite so far, I have been learning mariadb because I would like to migrate to that eventually.
Depends on the database, but it's a good idea to just open a connection when you need it. Less of a chance for corruption
@clever crypt an open uncommitted transaction is more likely to cause problems than an open connection
though some databases have a limit to the number of connections or cursors that can be open
@gleaming frost oooh that looks nice
@quaint swallow It works rly well. if you get stuck i can show you my code ;D
that would be awesome, i'm gonna play around with it first tho 👍🏻 👍🏻
Aight
@patent glen, thank-you. Sorry for the late reply. I'm at work and lunch break ended.
I considered my options, and I could have my application reconnect to the DB for each transaction. I haven't measured the overhead of that though, but it looks like that's how most web apps work.
Hey can I have help
my leaderboard command is not working
@client.command(pass_context=True)
async def leaderboard(ctx):
print("1")
res1 = conn.execute("SELECT Coins FROM Users ORDER BY Coins DESC;")
print("2")
res1 = res1.fetchall()
print("3")
embed = discord.Embed(title="Most coins", description="The top users with the most Coins", color=0xfffafa)
print("4")
res2 = conn.execute("SELECT UserID FROM Users ORDER BY Coins DESC;")
print("5")
res2 = res2.fetchall()
print("6")
for counter in range(0, 2):
print("7")
for member in ctx.message.server.members:
print("8")
counter_id = str(res2[counter])[2:-3]
print("9")
print(counter_id)
print("10")
print(member.id)
print("11")
if counter_id == member.id:
print("12")
embed.add_field(name=member.display_name, value=str(res1[counter])[1:-4], inline=False)
print("13")
break
await client.say(embed=embed)
print('15')
I tried printing the numbers for it to detect the error
but there is no error
and doesn't respond
Hype, here's what I've noticed so far. If you just one want result you can use fetchone() instead of fetchall()
you can combine your query
res.fetchone() # ("John Smith",10)```
someone help me about Heroku Postgres ?
I'm assuming of course that UserID is TEXT
Hype, if you have an interactive shell, you could also run
print(res.fetchone())```
just to make sure the table isn't empty
@hallow jetty
Depends on the database, but it's a good idea to just open a connection when you need it. Less of a chance for corruption
??????
Connect->Make changes->Save Changes-> Disconnect
I meant more the second part
Also, it depends on your application, if you have lots of connections to the database you want a pool, if it's now and again, closing and opening is fine
I'm by no means an expert, but I was just thinking about traffic not being saved if it crashes
@quaint swallow if u want something REALLY easy, use json files with the livejson module
Autocreates files and auto saves everything
Guys what is the best module to deal with MySQL. I care more about the features and components than difficulty like it’s ok if it’s hard
@clever crypt
res = conn.execute("SELECT UserID, Coins FROM Users ORDER BY Coins DESC;")
res.fetchone() # ("John Smith",10)
does it have to be exactly like this?
can I change the John Smith bit
the comment?
Hey can I have help
my leaderboard command is not working
@client.command(pass_context=True)
async def leaderboard(ctx):
print("1")
res1 = conn.execute("SELECT Coins FROM Users ORDER BY Coins DESC;")
print("2")
res1 = res1.fetchall()
print("3")
embed = discord.Embed(title="Most coins", description="The top users with the most Coins", color=0xfffafa)
print("4")
res2 = conn.execute("SELECT UserID FROM Users ORDER BY Coins DESC;")
print("5")
res2 = res2.fetchall()
print("6")
for counter in range(0, 2):
print("7")
for member in ctx.message.server.members:
print("8")
counter_id = str(res2[counter])[2:-3]
print("9")
print(counter_id)
print("10")
print(member.id)
print("11")
if counter_id == member.id:
print("12")
embed.add_field(name=member.display_name, value=str(res1[counter])[1:-4], inline=False)
print("13")
break
await client.say(embed=embed)
print('15')
I tried printing the numbers for it to detect the error
but there is no error
and doesn't respond
@glass hearth
this isn't normal discord.py?
Okay no problem thnx for trying
oh geeze you guys were in here too
https://hastebin.com/kixicisuro.py
For some reason it says that the database is locked when I do this command.
whats the full error?
Exception in command 'coinflip', database is locked
Just this
The command works fine on my main bot
I just copied to make some changes
https://www.sqlite.org/cvstrac/wiki?p=DatabaseIsLocked did you see this?
are both bots running at the same time?
not sure if thats the issue, but if you're on unix, you can run sudo lsof path/to/your/sqlite.db to check which processes have the database file opened
Yea but i use diffrent token for each. also the main bot is running in an other pc
Let me test that
Btw whats sudo? It doesnt recognize it
sounds like you're on windows, for that I don't know, sorry
if you're curious regardless, see https://en.wikipedia.org/wiki/Sudo
Should I close them and try again?
Closed them and tried again and it says its locked again
@ionic pecan I think i know why
I think its becasue I have this
conn = sqlite3.connect('test.db')
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
conn.row_factory = dict_factory
c = conn.cursor()```
in both files but if I dont have it I get error that 'c; is not defined
Or I just need c = conn.cursor() ?
But then I get conn is not defined
Fixed. I just import conn
Thanks
@slate bone I've found to have the best experience with pymysql
@hallow jetty having a pool of connections will not corrupt your data.
Thx
@full geyser nice, thanks for the tip!
I'm using Mongo rn
I was wondering, should create a user per collection
Or just 1 user with read/write access to every colllection?
@torn sphinx locked database means you have an open (not yet committed) transaction modifying that table on another connection.
you should always commit after doing modifications
by the other transaction
it's so that you don't read the table in an inconsistent state
with open("dat.json", 'r') as f:
data = json.load(f)
why do i keep getting this error?
my json file is simple and in the same directory
{
'id': 134,
'name': 'myname'
}
json can't have single quotes
oooooh
it's a very strict subset of javascript
so even though javascript allows single quotes or unquoted attribute names, double quotes are required
@ornate abyss Corrupt was the wrong word, but you're right. Pools are good. I was just thinking about a smaller db, like sqlite3, where you can only have 1 connection.
@hallow jetty You can have more than one connection for sqlite tho
Unless it's changed since a year ago (when I used) I remember having to deal with that restriction.
Ah I see, it just locks the Database.
You can only have one write at a given time, maybe thats what you meant
Yep
But as for connections, you can have multiple
Looks like it. Frameworks have spoiled me tbh
lol
Anyone familiar with a similar discord for SQL & Database help/discussion? Or are we able to ask non-python SQL related questions here.
Some of our #315249263103967242 might be more suitable if you're not working with python or the database directly
Thanks for the tip!
So I have a string in my json file with many objects:
{"users": [{"id": 1, "name": "Sandordude#7438", "str": 0, "weapon": "Dolch"}, {"id": 2, "name": "User2#4325", "str": 0, "weapon": "Weapon2"}, ...]}
how do I access for example "name"?
If I want to check if the name "Sandordude" is somewhere in the string
Sorry if I didnt express myself well in terms of terminology
I'm using the livejson module which allows me to modify this data as if it was a python list/dictionary
if "Sandordude#7438" in f["users"]:
print("You're already signed in")
return
anyway, this isn't the solution
Does users have to be a list in this case?
You could achieve much the same with it just being a dict
it can be the id
but user would be better
since it's easier for me as i'm not experienced at all
Anyways, with that structure you probably have to search the list
Traversing through the list and looking for user["name"] == "something"
hmm I guess, I just don't know how to program it since there's many "user" and users["name"] would basically look for an object that looks like this: {"name": something} inside of the [ ... ] array
Iterate over the list checking each users name, and break out when you find it to avoid checking unnecessary users
i'll find a way to do that 👍🏻 appreciate it
I can provide an example if you don't get it after trying a bit 😄
alright 😄 lets see if I can do it by myself
maybe tomorrow if you dont mind since I gotta go atm
also the structure of my json file must be horrible but whatever, it's my first time 😛
Np, feel free to tag me if im online (have work tomorrow so might not be)
You too c:
tyty
can someone tell me the module name for python to interact with MySQL database?
@hazy rock There are probably many. I like to work with SQLAlchemy.
We recommend sqlite3 for anyone who's new to SQL
It's already bundled with standard python installations and it's simple to use
for MySql specifically there are several different modules available
look at https://stackoverflow.com/questions/43102442/whats-the-difference-between-mysqldb-mysqlclient-and-mysql-connector-python for differences between them
If you search "python mysql" on google/yahoo/bing/ecosia (save the trees!), then you will get a lot of stuff regarding what you need
Guys can I use SQLite3 to store thousands of data ?
The word data isn't really a unit
You can
What about 100k ?
When the query time seriously affects the experience of the user I guess
Thanks mate
@slate bone What is your data
Because it really does depend on how much space each player would take up
SQL databases as considered the most effective way to store and access large amounts of data, although at a certain point where you do run into issues with query time, you should probably consider using better hardware as well as a more professional sql lib
Ermm I just want to store a list of names without any other data but the names may reach 100k
Like I feel it doesn’t really deserve MySQL
MySQL would be overly complicated if you're only storing names
I think sqlite3 should work, but you should probably do some research on what people benchmark
Ok thanks
Sqlite is more than capable
Are there any good tutorials out there on sqlite3?
The Python site's documentation mentions the one on w3schools but I'm always kind of wary about them
Yes
Let me rephrase that then, can someone provide a link to a good tutorial on sqlite3
Or rather, would someone please provide me a link to one
@unborn sentinel
In this Python SQLite tutorial, we will be going over a complete introduction to the sqlite3 built-in module within Python. SQLite allows us to quickly get u...
Any in written form? I'm not overly partial to videos since I do most of my coding while I'm at work
Apologies, I should have specified
It is basically in writing
@unborn sentinel when you say tutorial for sqlite, do you know SQL already and want to know how to work with the python library?
You know, after thinking about it, I'm not entirely sure what I meant. I guess I only have one specific use case in mind. Forget I asked, I think I figured out what I needed
Thanks though
All good
hey guys, i'm doing an if statement that goes like this: if message.content.startswith(-> key from python dictionary<-).. but I don't know what to put into the parentesis
can anyone help me out?
so it is not triggered if the key is not in the dictionary
if key in dictionary
if key in mydict and message.content.startswith(mydict[key])
or, if you want to be super clever and nobody can read your code
message.content.startswith(mydict.get(key,()))
hmm I know it's super simple but I got and still get some errors, thanks though
sorry for the easy questions
btw @dull scarab I was able to fix the problem so no more help is needed, thanks for your help!
I asked you to help me out the next day
🙏🏻
Uhm, what was it about 😅
it was about searching through lists, but my list was badly structured so I created a new one
and now it works
👌🏻 👌🏻
thanks
okay so it says "key" is not defined.. i'm not searching for a particular key but rather one that is part of the dictionary
I guess theres no easy way and i'll have to do a more complex if statement
for key, value in mydict.items():
if message.startswith(key):
...do something with value...
break```
i thought you already had a key, which may or may not be in the dict, and you were searching for something that started with the value corresponding to that key
@quaint swallow
hmm no, the if statement should be activated when a certain user input is part of the dictionary
hmm lets see :/
basically the outcome of the above mentioned code @patent glen is more than one key so if message.startswith(key) won't work
print(str(key))
outcome: e.g. key1, key2, key3
for example, the if (user_input) statement should be activated if the user_input equals to a key of my list
unfortunately I only have a "if message.content.startswith" statement
@quaint swallow move to the cogs version?
i've written quite a lot so far for my standards and i'd like to keep the syntax as it is @gleaming frost
i'm too much of a beginner for this :/
Is that how the command is triggered?
I can define the trigger how I want but I have to use "message.content.startswith" to recall the trigger
maybe it helps you to know what it's actually about
it's a discord bot and i'd like to create a command where one user "attacks" the other
so in order to check if the user that is attacked is part of the dictionary I have to do an if statement
I'm doing the exact same thing right now!
haha really? 😄
And I have learnt alot... From doing it twice
So if you want... I'll give you some advice?
if you don't mind
but I already have quite some code, the syntax basically is fixed now
if that makes sense
class Fights:
Instances = {}
Def __init__(self, player1, player2):
Self.p1 = player1
Self.p2 = player 2
Fights.instances[player1.id, player2.id] = self
Don't take that code as working, I'm on my phone
Then for the players....
class Players:
def __init__(self, author):
self.health = 300
self.damage = 20
self.author = author
@quaint swallow then you can just pass players names as message.author
And all the game stats
Will be stored in Fights.instances
Sounds like my first attempt... Lmao
it sounds great though 😛
I never worked with classes before
its my first time coding for real
Classes are great
I'm using that exact system for my own code.
It's very useful, and also makes your code surprisingly readable
yeah
Because then you can do p1.health ect
You could in theory make larger battles with that 2
@quaint swallow so what exactly were you stuck on?
I'll definitely hang to classes next time but I'm gonna try to end it "my way", even if it sucks
xD
my problem is that I don't know how to check if the user input is part of the class
haha yeah
Ok so
i'm using discord.py
Are you comparing it to a dict?
What does the key store?
this is what it looks like:
{"Marius#3523": [20, 1, "Mace"], "Sandordude#7438": [13837, 1, "Sword"]}
Ok so message.author
yea
for key in dict.keys():
if str(message.author) == key:
print("success")
else:
print(f"Debug {key} {message.author}")
Run that (might be mistakes on mobile)
Print debugging..... Xd
The value is the list
I did something similar just some time ago but I'll try again
ok
it always prints success for some reason
Debug Marius#3523 Sandordude#7438
success
Debug Marius#3523 Sandordude#7438
success
no matter what I type in this is printed
ooh wait
it should be message.content
if that exists
not author
haha np 😛
[2:29 AM] Sandordude: Marius#3523
[12:29 AM] Sandordude: sdgsd
success
Debug Sandordude#7438 Sandordude#7438
Debug Marius#3523 Sandordude#7438
Debug Sandordude#7438 Sandordude#7438
it works now
Send me your code.
ok
#Fight
for key in users.keys():
if str(message.content) == key:
print("success")
else:
print(f"Debug {key} {message.author}")
Ok so
still dont know how to insert the code in a more fashionable way in discord
yeah
Basically it should only print debugging if it fails
actually it should have worked because the second time i just wrote nonsense
"jadsjaskjf"
yes exactly
Wait show one output
ok
And your dict
```python
That's how you show it
Top line ```python
Bottom line ```
Sandordude#7438
nice
ok so
Debug Marius#3523 Sandordude#7438
success
after I wrote
Sandordude#7438
damn, sorry 😄
It should show the debug one
Because it's a for loop
So even tho the first one worked
The rest will still run
To fix that, add break after the print success
And you can safely get rid of the else and debug, because we know it's working now.
yea, nice!
okay so i'm going to find out how this copes with !fight User
should work tho
thanks so much!
We should see eachothers bots?
yeah I was just about to propose that
lemme send you mine
its a beginner one though so its gonna be confusing
@gleaming frost how did you get the ``` itself inside a code block?
what in the gas
what are databases
A database is another bit of software running on your computer which has been designed to hold, well data.
@torn sphinx What exactly is it you wanted to know?
What do you mean by what type
It can hold any type of data
so if i made a login screen it needs a database to send all the usernames and pw's to the database
so i get all their info?
Yeah if you want to store
how do i make a database?
idk
For database you can try sqllite
o shit no sql
Database softwares are different
easy coded ones?
k thanks for help!
SQLite will be perfect for this
You dont have to do any complicated joins or anything
good
So i am working on adding "Memory" to my discord bot
And i am working on a function that loads new information into the database to be pulled on boot as "Memory"
It executes every few minutes
But how would i cross check information like this with the database
{'344289705627484163': {'IGN': 'Squint', 'FC': 'SW-0000-0000-0000'},}
I am using SQLite3 BTW
But basically my "Memory" for Profiles is a very long version of that
But i would need to check what parts of it aren't in the database, and update/insert accordingly
I actually got a idea on how to do this, but its gonna be annoying
Ok, so i got a issue
When i do a fetchall all items come as this
(101020, 'Unset', 'SW-0000-0000-0000', '1', 'C-', 'C-', 'C-', 'C-', None, 'https://cdn.discordapp.com/attachments/444297968049455125/459864703821414402/banner-octo.png', 'No,')
I might have figured it out though
So do you still need help?
Yeah i still need to figure out how to check this information correctly
Cause i can now Format the Information in any way i like
Check this information correctly?
So basically what i want is a loop that checks for anything new and updates if it finds anything new
Its for "Memory"
Does the bot have separate processes that would change this memory
Or is it all through the bot
It has commands that would modify the "Memory"
Alright, so why not change the parts that need to be changed on the commands
self.bot.SplatNetQueue.append(ctx.message.channel.id)
Instead of inserting and querying
Cause i use SQLite which is blocking
Or something
So i want to use the least amount of SQLite3 as possible
cur.execute('INSERT INTO Queue(Channel) VALUES(?)', (ctx.message.channel.id,))
conn.commit()
self.bot.SplatNetQueue.append(ctx.message.channel.id)
People have said doing stuff like this in a command is bad
But what I'm guessing you're doing, is on the command updating the database and then selecting everything again?
What that right there is doing is Updating the Database then adding to memory
Right
What people said is i should make a loop that executes every like 5-10 Minutes that checks the difference between the "Memory" and the Database, then updates/inserts new info
Are you simply just inserting a new row each time something happens?
I see that "unset" in there a few times
Updating too
'[[[101018]]] - [[[Mang]]] - [[[SW-0000-0000-0000]]] - [[[41]]] - [[[A]]] - [[[S+0]]] - [[[A+]]] - [[[A]]] - [[[None]]] - [[[https://cdn.discordapp.com/attachments/444297968049455125/459864703821414402/banner-octo.png]]] - [[[No,]]] - ', '[[[101019]]] - [[[Cube]]] - [[[SW-3234-2940-3525]]] - [[[18]]] - [[[C-]]] - [[[C-]]] - [[[C-]]] - [[[C-]]] - [[[None]]] - [[[https://cdn.discordapp.com/attachments/444297968049455125/459864703821414402/banner-octo.png]]] - [[[No,]]] - ', '[[[101020]]] - [[[Unset]]] - [[[SW-0000-0000-0000]]] - [[[1]]] - [[[C-]]] - [[[C-]]] - [[[C-]]] - [[[C-]]] - [[[None]]] - [[[https://cdn.discordapp.com/attachments/444297968049455125/459864703821414402/banner-octo.png]]] Thats what all of this stuff is for
"Profile" items
I mean, that looks horrific on phone
Thats just a new reformat
Right
cur.execute('SELECT User, IGN, FC, Level, RM, SZ, TC, CB, Gender, Banner, Title FROM Profile')
PrintCur = cur.fetchall()
ReformatList = []
for item in PrintCur:
Var = ''
for item in item:
Var += f'[[[{item}]]] - '
ReformatList.append(Var)
print(ReformatList)
Thats how it loads the "Memory"
Do you think i should be doing this every few minutes load into the database thing?
Or should i just stick to using Update Database Update memory on command
Update on command
@utility.command(name='splatnet-add')
@commands.has_permissions(administrator=True)
@commands.cooldown(1, 5, type=BucketType.user)
async def splatnet_debug(self, ctx):
conn = sqlite3.connect(f'{self.bot.V}/tartar.db')
cur = conn.cursor()
if ctx.message.channel.id in self.bot.SplatNetQueue:
cur.execute('DELETE FROM Queue WHERE Channel=?', (ctx.message.channel.id,))
conn.commit()
self.bot.SplatNetQueue.remove(ctx.message.channel.id)
embed=discord.Embed(color=discord.Colour.dark_grey(), )
embed.set_author(name=self.bot.config.name, icon_url=self.bot.config.url)
embed.add_field(name='SplatNet Channel Deleted!', value=f"{ctx.message.author.mention} the Channel {ctx.message.channel.mention} is no longer a SplatNet2 Channel!", inline=False)
await ctx.send(embed=embed)
else:
cur.execute('INSERT INTO Queue(Channel) VALUES(?)', (ctx.message.channel.id,))
conn.commit()
self.bot.SplatNetQueue.append(ctx.message.channel.id)
embed=discord.Embed(color=discord.Colour.dark_grey(), )
embed.set_author(name=self.bot.config.name, icon_url=self.bot.config.url)
embed.add_field(name='SplatNet Channel Created!', value=f"{ctx.message.author.mention} the Channel {ctx.message.channel.mention} is now a SplatNet2 Channel!", inline=False)
await ctx.send(embed=embed)
cur.close()
So this would be the best way
If i wanted to update something
This is the simplest one i got
401872749720502272: {'User': 101020, 'IGN': 'Unset', 'FC': 'SW-0000-0000-0000', 'Level': '1', 'RM': 'C-', 'SZ': 'C-', 'TC': 'C-', 'CB': 'C-', 'Gender': None, 'Banner': 'https://cdn.discordapp.com/attachments/444297968049455125/459864703821414402/banner-octo.png', 'Title': 'No,'}}
This is the most Complicated one i have
@orchid charm is this a public bot?
My only reason is anyone on any server with admin perms can use it
@gleaming frost This is not the Public Version
alright
There is a Open Source Splatoon Bot that has some remakes of code from the private one
Working on Implementing code from the Private one to the Open Source One
Thats the current status of the Open Source Version
I am considering just using a JSON Database for this one, but SQLite is still simpler
@gleaming frost
This program is p easy to set up
And the code that currently is in it is decent
I am working on more efficiency stuff in it
@commands.group(aliases=['profil', 'account'], invoke_without_command=True, ignore_extra=False, case_insensitive=True)
@profile_check()
@bot_user_check()
async def profile(self, ctx, user: discord.Member=None):
try:
conn = sqlite3.connect(f'{self.bot.directory}/splatoon-bot.db')
cur = conn.cursor()
if user == None:
user = ctx.author.id
Check = self.bot.get_user(user.id)
cur.execute('SELECT IGN, FC, Level, RM, SZ, TC, CB, Banner FROM Profile WHERE ID={0.id}'.format(user))
IGN, FC, Level, RM, SZ, TC, CB, Banner = cur.fetchone()
cur.close()
embed=discord.Embed(color=discord.Colour.teal(), title=f"{ctx.message.author.name}'s Profile")
embed.set_author(name=self.bot.config.name, icon_url=self.bot.config.url)
embed.add_field(name=f'Username:', value=f'{IGN}', inline=True)
embed.add_field(name=f'Friend Code', value=f'{FC}', inline=True)
embed.add_field(name=f'Ranked Statistics', value=f'Rainmaker: {RM}\nTower Control: {TC}\nSplat Zones: {SZ}\nClam Blitz: {CB}', inline=True)
embed.add_field(name=f'Level', value=f'Level: {Level}', inline=True)
embed.set_image(url=Banner)
await ctx.send(embed=embed)
except TypeError:
embed=discord.Embed(color=discord.Colour.teal(), description=f'Specified user does not have a Profile!')
embed.set_author(name=self.bot.config.name, icon_url=self.bot.config.url)
await ctx.send(embed=embed)
Like working on making the Profile Command Group less big and clunky
CREATE TABLE IF NOT EXISTS servers (
server_id BIGINT CONSTRAINT server_pk PRIMARY KEY,
submission_channel_id BIGINT,
prefixes VARCHAR[],
max_rating INTEGER
)
I would like to be able to know if the table was created. Am using asyncpg, does CREATE TABLE return something?
ping me
Well if you execute without an error surely it’ll work right?
@torn sphinx
it doesn't matter
IF NOT EXISTS removes that error
anyways just gonna ignore it
Ok
How should I check if a column in my database equals something and if so add to another column.
what have you tried already?
i mean, it's kinda hard to figure out what exactly you're trying to do, because your question isn't completely clear
@rough river can you give us some more context?
I have an adventure command that generates enemies killed and deaths and from that I determine the xp earned but I don't want to have people with high amounts xp so I want the level to go up every time the xp hits a certain number. The number I'm comparing it to is the level x 500 + 500 .
You would first query their xp and level, add to their xp (and level if needs be), and update their values again
@rough river
But how could I check if xp is equal to the amount of xp needed to level up
Would I have to do if: or i there an easier way
An if yes
I just learnt python's syntax
and all these codes you guys are sending me
is scaring the shit out of me..
???
best way to handle alot of pictures without compressing?
its about databases?
how is it about databases?
^
@torn sphinx Load them as BYTEIO's?
can someone explain this to me?
where does that 'current_timestamp' column name even comes from?
current_timestamp is built in to sqlite
it doesnt make sense otherwise
so it will just yield the current timestamp?
I'm completely new to db, what I want to achieve is to store and read a timestamp
sqlite doesn't really have a timestamp type
current_timestamp returns a string
the section you are reading indicates that you can store datetime objects in the database
it clearly has a timestamp type and even a current timestamp if it does this
wait, nevermind
ok it's not a real type
it's just a tag that tells python how to read it out
the as "...[timestamp]" is the important part of that example
what does it do?
it sets the type tag, which python then uses to look up the converter that turns it into a python datetime object
the value is still stored in the database as a string
you have to have used sqlite3.PARSE_COLNAMES in the connection
thanks
PARSE_COLNAMES is for the "[timestamp]" thing, PARSE_DECLTYPES is for the create table types
Hey, does anyone use SQLAlchemy
I'm wondering if I should have one instance of engine and base in some "database.py" that my classes import from, or if each class should have their own instance
if anyone has any input pease @ me
i want to create a table with n number of columns, handy way to do that?
c.execute('CREATE TABLE options (poll_id, {})'.format(gen_options()))
can I do it withotu .format?
@torn sphinx @patent glen
"it clearly has a timestamp type and even a current timestamp if it does this"
Sqlite does not have a timestamp datatype, what it has are functions capable of manipulating the other data types
of course I meant that it has adapters for datetime
Glad we got that sorted
@torn sphinx To be clear, my point was that the adapter is built into the python sqlite3 library, not sqlite itself. You won't necessarily find it in other languages, and similar features in other languages may not work the same way.
Am I able to talk about database schema here?
I wanna talk ideas with people who are here, just in case I'm actually losing my mind on my ideas.
Just in case I get a !tag ask, I'm only asking because I don't know if I'm allowed to here.
i don't see why not
(we've definitely had discussions of database schemas here and in help channels before as a result of X-Y problems before and no-one's considered it off-topic iirc)
Alright, coool.
So, I plan on having a database for my Discord bot that will store Dungeons & Dragons character information. I'm fairly certain that I want to store everything per-server, and not let characters find their way into other servers, but I haven't quite decided on it. I do know, however, that I would like certain per-server configurations stored within this database as well. I'm not sure if I should have more than one table to manage each of these. This is my idea for table schema so far:
what kind of database is this?
like, sql doesn't have a tree structure like that, but you could consider multiple columns (server id, user id, character id) all as part of a single key
This is a rethinkdb database.
RethinkDB is a JSON-based NoSQL database.
I guess you could model the tree structure in SQL with foreign keys. characters would have a foreign key to users, for example
and users could have a composite pk (guild_id, user_id)
seems like it only supports tornado and twisted
What are they?
wrong.
Seems you can use twisted, tornado, gevent and asyncio
tornado, twisted, gevent and asyncio, yep
Yep.
How do i use asyncio?
I haven't really used it
So don't understand what it does
!help
Doc:
docs Lookup documentation for Python symbols.
Information:
roles Returns a list of all roles and their
server Returns an embed full of
Snakes:
snakes Commands from our first code jam.
Utils:
pep Fetches information about a PEP and sends it to the channel.
No Category:
help Shows this message.
Type !help command for more info on a command.
You can also type !help category for more info on a category.
Well probably the wrong channel, but asyncio is a library which allows you to setup an event loop, and use coroutines instead of the traditional synchronous programming
async with r.connect(db='marvel') as conn:
await r.table('superheroes').run(conn)```
I think that would work?
Should do
mind ive never used the rethinkdb library, so take that "should do" with a pinch of salt
you dont have to say sorry haha, i just wanted to make sure
But you could get some cases like for example, not awaiting asyncio.sleep, it wont technically break anything, it just will return a coroutine and not actually sleep
You wouldnt block from forgetting to await an async function, you would block if you tried to run a synchronous function in an async setting
So using the same example above, if you used time.sleep over asyncio.sleep you would block the whole thing
Yeah
@viral crag the linked page only described tornado or twisted, not sure how I should figure that other stuff out.
@torn sphinx use bot commands in #bot-commands, not here
That document tripped me up as well
But, apparently, you can just set it and forget it with async, instead going with a web- or network driver.
Didn't get around to playing with it last night, though. Too much going on at home, went to sleep early.
I'm making a polling feature for my discord bot, it uses a sqlite database, how do I structure the database so I can check if a member has already voted?
we're gonna need some more context to help you with that
do you have any schema yet? or an idea how you want to lay it out?
for now I only have those two tables: polls (author, question, start_date, exp_date ..) and votes(option, vote_count)
Where do you store the votes of users?
in the database?
You clearly don't
You're just storing the count of the votes
You have to store each individual vote
first you want a foreign key within the votes table to link back to the poll (a user can have more than one vote if there are many polls or even many votes per poll if thats allowed(?)) and then secondly you will need to store the user with the vote else its purely just an anonymous tally of votes
I'm unsure what the options table is for
And you probably want to store the users ID on the vote
aren't they stored?
every poll can have many option and every option can have many votes so..
Yes, so if you store the user id on the vote then you know who voted
And the votes would have a relation with the poll
votes have realtion with the poll through options, and I don't really need to know who voted for what, user_id would be discord_id
And you probably want to store the users ID on the vote yep ignore that completely missed the user_id
As for options, what is stored in there?
he stores individual choices, options in a poll
so in a poll "which letter is the best?" A, B or C are the "options"
Using sqlite3 when creating a table, what is the difference between PRIMARY KEY and UNIQUE?
@sacred heart several
primary keys also can't be null
a table can only have one primary key
a WITHOUT ROWID table uses the primary key as the main index (i.e. how the rows are organized in the table)
look at https://www.sqlite.org/lang_createtable.html for more detailed information
conceptually, a primary key is supposed to be the single set of values that characterizes a row in the table
so it decides how a table is organised?
it can
im not sure if i still understand sorry, is it for example a main set of values? and the others are secondart
*secondary?
hey all, just getting started in sqlite, created a db, added an item and am running a method to check if it has the 'owned' tag set to 1, not sure I'm doing it correctly, could someone breakdown the c.execute line for me?
import sqlite3
from items import items
conn = sqlite3.connect('items.db')
c = conn.cursor()
# c.execute("""CREATE TABLE items (
# id integer,
# name text,
# attack integer,
# elemental_damage_type text,
# elemental_damage_amount integer,
# parry_rate integer,
# block_rate integer,
# critical_attack_rate integer,
# critical_attack_modifier integer,
# bodypart text,
# defense integer,
# description text,
# equipped integer,
# owned integer,
# price integer,
# type text,
# subtype text
# )""")
def item_by_owned(owned):
c.execute("SELECT * FROM items WHERE owned=:owned", {'owned': 1}) #comment here which each section means please?
return c.fetchall()
inventory = item_by_owned(1)
print(inventory)
conn.close()
c.execute("SELECT * FROM items WHERE owned=:owned", {'owned': 1}) this part isnt right unfortunately
Where you want to substitute a value, you place a ?, and you give it a tuple of values you want to pass
c.execute("SELECT * FROM items WHERE owned = ?", (1,))
@young scarab
oh hang on
nice, thanks
apologies, i missed the :
you're using the named parameters instead
Let me rephrase, instead of the ?, you have :name this will map whatever name is to a value within the dictionary that you pass
so in your case, :owned, will find the value of owned within the passed dictionary, which for you is 1
@young scarab apologies
np, thanks
i thought that was it, but wanted to make sure, trying to do things the right way
i take it the above is more pythonic than:
c.execute("SELECT * FROM items WHERE owned = 1")
though both accomplish the same
Well its not the case of being pythonic, its to stop SQL injection
If you were you use string formatting, you could end up with a query like so
SELECT * FROM items WHERE owned = 1; DROP TABLE x;
with parameter substitution, only one SQL keyword (SELECT, DROP, INSERT) will be ran, so whatever the user passes will be treat as data, and data only
its all good
So, using rethinkdb. Is there anyway to order_by an embedded field? So say I have this http://b1nzy-banned.me/B0LqZ.png and I want to create a list of the players total_xp in descending order
think you could use merge to pull that off https://rethinkdb.com/api/python/merge/
@daring cairn
Hmmmm
here's a JS API example doing something similar https://stackoverflow.com/questions/33351037/sort-nested-timestamps-in-a-query
Alright I'll give it a shot in a few here, thanks
Anyone good with psql and flask-sqlalchemy?
I’ve got a model in sqlalchemy info=column(Binary() nullable=False) how do I create this table in psql? I was thinking create table test( info varchar(1000) NOT NULL
Pretty sure that’s wrong
SQLalchemy should make the tables for you
How
ok I don't get it
what syntax do I need to use in order to get a datetime.datetime object from sqlite3
There is something within the sqlite3 module for python, so you do like so
c = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
cur = c.cursor()
cur.execute("CREATE TABLE x (time timestamp)")
cur.execute("INSERT INTO x VALUES (?)", (datetime.datetime.now(),))
cur.execute("select time from x")
row = cur.fetchone()
And then row is a tuple containing the datetime
@torn sphinx
I think the only thing I have different is that I have additional 'sqlite3.PARSE_COLNAMES |'
If you run that ^, it returns a datetime object
How would you write a MySql query to return the second purchase item per each customer? Excluding customers who purchased only 1 time
So do you want all items from people who bought more than one item?
Or only the second item from people who bought 2 or more items?
second item from people who purchased at least 2 times.
Okay, so you would so something like this
SELECT rows FROM table WHERE customer = some_id ORDER BY id LIMIT 1, 1
Where, rows are the rows you want, table is your table name, customer is the column which relates to the customer, some_id is the customer you are searching for, id is the primary key of the items
Actually i didnt account for more than one item
oh wait nvm, the offset will just return nothing
I was thinking similarly.. but it would only give me 1 row instead of all the customers
Hm
@noble anchor something like, sql select c.*, p4.* from customer inner join purchase p4 on p4.cust = c.id inner join ( select p1.customer_id, min(p2.seq) seq from purchase p1 inner join purchase p2 on p1.cust = p2.cust and p1.seq < p2.seq group by p1.customer_id) p3 on p3.cust = c.id and p3.seq = p4.seq
that's probably horrifying and low-performance, but i'm not sure there's a good way to get what you want
How do you view rethinkdbs files on server save?
Is there a way to write symbols like these in SQLite db? when i copy them and put them in db, they change
@tacit dagger most of them are probably unicode, go to character map and scroll down with, like, Arial Unicode MS selected as the font
it looks like you're looking at, like, wingdings, now, which won't work
ah thanks 😃
👍
(wingdings is a font that just has symbols replacing all the regular characters)
Dumb question, is it normal to do sqlite3 connections using with or is that considered bad form?
its probably fine
@unborn sentinel You can use the connection with a context manager, it will automatically commit the changes if it was successful or it will rollback if an exception is raised
so to answer your question, its perfectly fine
yea its nice, mind if an exception is raised, you still need to catch it, so just be aware of that
-nods- Right
Thanks, that gives me a bit more confidence in working with this prototype
It's all good
how do I start using postgres?
you install it and do operation son it with SQL using either a dedicated console or some postgres connector for a programming lang
or what do you mean
I cant get it to work at all
I do sudo -u postgres -i
then initdb -D '/var/lib/postgres/data'
then it throws permission error for some reason
ffs
@noble anchor derive a table that selects only people with a count of > 1 row with their ID in it. Then from that select with a LIMIT of 2, and sort the derivsed results in reverse order, then select from that newly derived table a LIMIT 1
should end up with only 2nd position entries from people with 2 or more entries
so, SELECT rows FROM (SELECT rows FROM table WHERE peoplehavemultiplerows ORDER BY thenumber ASC LIMIT 2) ORDER BY thenumber DESC LIMIT 1
@summer sable I couldnt see that working
peoplehavemultiplerows how do you get this section without a GROUP BY, and the LIMIT 1 on the end of the query will limit the whole thing i would imagine
it would probably require a second nested derived table, yeah
but no, the limits definitely work locally, i've done that before
it will limit your end results to 1 overall, but that's what you want
oh wait i see what you mean, yes it won't work for a whole group of people hmm
SELECT cust.*, orders.* FROM cust JOIN orders ON cust.cust_id = orders.cust_id
WHERE orders.order_id in (SELECT order_id FROM orders o2 WHERE o2.cust_id = cust.cust_id ORDER BY o2.order_id limit 1, 1)```
he doesnt want 1 row overall tho
yeah i caught on just above
else what i said would have worked :)
@noble anchor ```sql
CREATE TABLE cust(cust_id INTEGER PRIMARY KEY);
CREATE TABLE "order"(order_id INTEGER PRIMARY KEY, cust_id INTEGER);
INSERT INTO cust VALUES(1);
INSERT INTO cust VALUES(2);
INSERT INTO cust VALUES(3);
INSERT INTO cust VALUES(4);
INSERT INTO "order" VALUES(101, 1);
INSERT INTO "order" VALUES(102, 1);
INSERT INTO "order" VALUES(103, 1);
INSERT INTO "order" VALUES(202, 2);
INSERT INTO "order" VALUES(401, 4);
INSERT INTO "order" VALUES(402, 4);
SELECT c., o. FROM "cust" c JOIN "order" o ON c.cust_id = o.cust_id
WHERE o.order_id in
(SELECT order_id FROM "order" o2 WHERE o2.cust_id = c.cust_id ORDER BY o2.order_id limit 1, 1);
1|102|1
4|402|4
full example to show this technique works
and here's the one I posted yesterday, adapted to this sample table schema - also works ```sql
select c., o4.
from cust c
inner join "order" o4 on o4.cust_id = c.cust_id
inner join (
select o1.cust_id, min(o2.order_id) order_id
from "order" o1
inner join "order" o2
on o1.cust_id = o2.cust_id and o1.order_id < o2.order_id
group by o1.cust_id) o3
on o3.cust_id = c.cust_id and o3.order_id = o4.order_id
order is a keyword
ah of course
sql differentiates between single and double quotes doesn't it?
or is that different from database to database
officially
double quotes are for column names and table names
single quotes are for strings
I think sqlite blurs the lines a little bit
"standards" 😛
[S]ingle quote for [S]trings, [D]ouble quote for things in the [D]atabase
i remember reading that on a stackoverflow post once and it stuck with me
oh thats a good thing to remember 👍
sqlite holds those interpretations, but lets you use the other one if it's unambiguous
select 'foo' from bar is always a string
select "foo" from bar is a string only if there is no foo column.
select foo from 'bar' is legal and refers to the table because you can't select from a string
select `foo` from bar always refers to a foo column
select [foo] from bar always refers to a foo column
right, sqlite is unusually permissive here
i'd guess that select "foo" won't give you a string either, if there's no foo column
wait huh it does
so mysql is more permissive than, say, oracle
I cant say ive used oracle so ill take your word
i use it at work and just tried it
👌
I'm mucking around with rethinkdb after using JSON files for my discord bot
I have multiple problems:
Is it better for rethink to handle all the searches for data in the file, or is it more effective to let python handle the searching
What's the best way to get it to generate empty data sets for me to pass dicts in later?
If you have more questions about what I'm doing, just @ me
you should offload as much processing to the database as you can
after all, that is what the database is best at
it's worth noting that even using rethinkdb's lambda filtering stuff will still run the lambda on the server
it parses the AST and translates it to something the query engine can use
that sounds pretty advanced
so how exactly would I store ip addresses into a database?
or I guess, what kind of data type would I do?
assuming I'm using 1pv4
doing something like this: for i in c.execute("SELECT * FROM tableWHERE IP = {}".format(ip)):
gives this error: sqlite3.OperationalError: near ".0": syntax error
You really shouldn't use string formatting for your queries
yea, but still, it was just an example
You can store the ip as an int, or text.
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 9 supplied.
the length of the string that happens to be the ip is 9
What did you try?
for i in c.execute("SELECT * FROM sessions WHERE IP = ?", ip):
and ip is a string?
What type is IP in your db
I've tried changing it between text and int
oh right, wrap your argument in a tuple ... WHERE IP = ?", (ip, )):
Fixed it?
yep
👌🏾
is Sqlite3 good for managing database for a Sells Management Program ?
No, you should use an actual DBMS instead, like Postgre or mysql
most "is sqlite3 good for ..." questions can probably be answered pretty well by their own page "Appropriate Uses For SQLite": https://www.sqlite.org/whentouse.html
however, for any commercial or larger-scale program, I'd just do what KnownError suggested
So over the past month, I've blown through introductory python books and videos and I feel pretty comfortable with it now. I'm interested in learning about Data structures and networking stuff, does anyone know of a series of videos that I could checkout? I don't mind books either.
I've tried looking stuff up about the topic but it seems like anytime I google what something is, I need to know what 10 other things are just to understand it. I there a linear way I can build up to these things?
If you're interested in learning networking, this playlist is good: https://www.youtube.com/playlist?list=PLmdYg02XJt6QRQfYjyQcMPfS3mrSnFbRC
Just ignore/skip the Cisco/CCNA parts
Also this discussion is rather off topic for #databases
Honestly wish we had a networking channel
But we don't, so one of the off topic channels would suffice
Thank you! This is exactly something I was looking for. Sorry about that, didn't know where to ask.
No worries
I seem to be encountering a problem with the rethinkdb database driver.
I'm attempting to set the loop type of the module to asyncio, as shown in the documentation,
r.set_loop_type("tornado")
conn = r.connect(host='localhost', port=28015)```
but when I do, I get this error:
```Traceback (most recent call last):
File "C:/Users/Vincent/Desktop/Python/Projects/DnDBot/bot.py", line 8, in <module>
r.set_loop_type('asyncio')
File "C:\Users\Vincent\AppData\Local\Programs\Python\Python37-32\lib\site-packages\rethinkdb\net.py", line 677, in set_loop_type
module = imp.load_module('rethinkdb.' + moduleName, moduleFile, pathName, desc)
File "C:\Users\Vincent\AppData\Local\Programs\Python\Python37-32\lib\imp.py", line 235, in load_module
return load_source(name, filename, file)
File "C:\Users\Vincent\AppData\Local\Programs\Python\Python37-32\lib\imp.py", line 172, in load_source
module = _load(spec)
File "<frozen importlib._bootstrap>", line 696, in _load
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 724, in exec_module
File "<frozen importlib._bootstrap_external>", line 860, in get_code
File "<frozen importlib._bootstrap_external>", line 791, in source_to_code
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\Vincent\AppData\Local\Programs\Python\Python37-32\lib\site-packages\rethinkdb\asyncio_net\net_asyncio.py", line 114
asyncio.async(self.conn._parent._continue(self))
^
SyntaxError: invalid syntax```
...so I can't use rethink with 3.7?
you'll find plenty of things you can't use with 3.7
seems to be the relevant issue
That was the fix.
Fixed the version that I'm on; guess I'll have to include it in the bot's files.
Thanks.
Hello all, i open i db file with hex editor and i notice the PΠ in the beggining. What type of db is this?
Try running the file command on it
It can identify a lot of file types using a list of magic numbers
@versed coyote turns out he was trying to open thumbs.db 😄
if i understood him correctly he said the file was called thumbs.db
he just didnt mention that at the beginning
started off saying that it has a .db extension and was a hidden file
i tried too
it doesnt match up
but who knows how his text editor interpreted the file
yup
i suggested opening it in a hex editor but that never ended up happening
anyway he seemed to drop it once he realised it was just thumbs.db
Yeah...
I just deleted my database
and I made new one
and it isn't coming up
any help
Cause I am using the DB Browser for SQL
But I try open the database but it won't do it
cause there is no database
but all my database commands work
@dull scarab
conn = sqlite3.connect('Coins.db', isolation_level=None)
c = conn.cursor()
conn.execute("""CREATE TABLE IF NOT EXISTS Users(
UserID TEXT,
Coins INTERGER)""")
All my database commands work
It is just I wanted to create a new database
And it's not creating a file?`
If your commands are working, surely it's creating it somewhere
hm?
Does the commands, that use the database, work?
I'm using PostgreSQL and the following
SELECT banks.bankname, banks.logininformation, accounts.accountid FROM banks INNER JOIN accounts ON accounts.bankid=banks.id WHERE banks.scriptname = 'banking_scrape.banks.paypal';
is throwing an error. I assure you the column does exist!
[2018-08-05 19:45:06] [42703] ERROR: column accounts.bankid does not exist
[2018-08-05 19:45:06] Hint: Perhaps you meant to reference the column "accounts.bookid".
Nevermind. Was looking at the wrong schema.
Yes @dull scarab sorry for late answer
Then you must have a db file somewhere, unless it's magically referring to a memory db
I'd love to help you figure it out, but I was just getting off :(
Try reposting the question, maybe someone else can help
Okay
I'm using SQLite3, and I have a bunch of guild id's, how would I get a value from that id?
Like, there's a column called id's and I'm trying to get the row with a specific value
(sorry, im new to this)
SELECT rowname FROM table WHERE rowname = specific id
Sorry for no markdown, on phone
ah, thank you
Np
how do i make sqlite get a value only if it exists?
what do you mean by exists
nvm
if a row doesn't exist, fetchall will return an empty list or fetchone will return None
I'm trying to make a change prefix command
@has_permissions(manage_guild=True)
@edit.command()
@guild_only()
async def prefix(self, ctx, prefix: clean_content):
if len(prefix) > 5:
return
conn = sqlite3.connect('guilds.db')
c = conn.cursor()
c.execute(f"REPLACE INTO guilds (id, prefix) VALUES ({ctx.guild.id}, '{prefix}');")
conn.commit()
conn.close()
await ctx.send(f":settings: Changed prefix to `{prefix}`")
I have this code, but whenever I run it, it sends the confirmation message at the end, but it doesn't actually change the prefix. Why is that?
ah, ok
would it be c.execute(f"UPDATE guilds (id, prefix) VALUES ({ctx.guild.id}, '{prefix}');")?
Not quite no
c.execute("UPDATE guilds SET prefix = ? WHERE id = ?", (prefix, ctx.guild.id))
You should never use string formatting with SQL queries by the way
why?
Leaves you wide open to SQL injection
all good

