#databases
1 messages · Page 58 of 1
you can create and a write lines to a text file like so:
with open('some_file.txt', 'w') as file:
for i in range(10):
for j in range(10):
print('i:', i, 'j:', j, file = file)
# or alternatively:
file.write(f'i: {i} j: {j}\n')
a few other things come to mind.
if you have lots of rows in your database fetchall wouldnt be the best option for iterating through them all.
instead you can iterate through them one by one.
one way (and the simplest way) this can be done is by iterating over the cursor:
cursor.execute('SELECT * FROM Customer')
for row in cursor:
# do things here
you can also go one step further and unpack the row right there in your loop:
for user, password, balance, postcode in cursor:
# do things
@spare geode
one by one will be slow for other reasons
fetchall will be the fastest if you can fit the whole result in memory
otherwise you should use fetchmany with a batch size
def textfile(Admin):
file = open("testfile.txt","w")
print ("This shows ALL data including Stock that isnt in store anymore!")
with sqlite3.connect("EMP.db") as db:
cursor = db.cursor()
cursor.execute('SELECT * FROM Customer')
data = cursor.fetchall()
iterate=0
for x in (data):
file.write(f"User: {data[iterate][0]} Password: {data[iterate][1]} Balance: {data[iterate][2]} Overdraft: {data[iterate][3]} Postcode: {data[iterate][4]}\n")
iterate+=1
Just opened the file then replaced the print with write
Works alright
ty for help ❤
cursor.execute("""CREATE TABLE IF NOT EXISTS results(n0 INTEGER, n1 INTEGER, n2 INTEGER, n3 INTEGER, n4 INTEGER, n5 INTEGER,
n6 INTEGER, n7 INTEGER, n8 INTEGER, n9 INTEGER, n10 INTEGER""")```What's wrong with this? Says error near `INTEGER`
n6 INTEGER, n7 INTEGER, n8 INTEGER, n9 INTEGER, n10 INTEGER""")
sqlite3.OperationalError: near "INTEGER": syntax error```
(@me upon response please)
missing closing )
thx
the world needs a good sql syntax checker
even the almighty postgres has absolutely crap syntax error reporting
n0_fail = cursor.execute("""SELECT * FROM results WHERE n0 = 0""").fetchall()
n0_success = cursor.execute("""SELECT * FROM results WHERE n0 != 0""").fetchall()
n1_fail = cursor.execute("""SELECT * FROM results WHERE n1 = 0""").fetchall()
n1_success = cursor.execute("""SELECT * FROM results WHERE n1 != 0""").fetchall()
n2_fail = cursor.execute("""SELECT * FROM results WHERE n2 = 0""").fetchall()
n2_success = cursor.execute("""SELECT * FROM results WHERE n2 != 0""").fetchall()```Is there a better way of doing this (rather than having to do everything separately, it retrieves all info and stores in appropriate variable)
you could append a column indicating whether each of the n variables is 0
and then download the whole thing and do filtering client side
if the data isnt too big to fit in memory that will be simpler than doing a single query. and if you use pandas it will be pretty fast
How exactly would that work? (I'm really new to databases)
actually wait hold on
just include the N variables in the output
and filter
literally just `select * from results', load into pandas, and filter
idk anything about pandas and filtering
So that doesn't really help either
@harsh pulsar
well you dont need to use pandas then
but if you just wanna know how to filter a list thats a topic for one of the help channels.
data = cursor.execute("""SELECT * FROM results""").fetchall()
print("".join(str(data)), sep="\n")```How to get it to print on different lines?
This still prints it all on one line
It currently prints py [(0, 0, 1, 0, 2, 1, 1, 1, 1, 1, 2), (0, 1, 1, 0, 3, 0, 1, 1, 0, 1, 2), (1, 1, 1, 1, 0, 2, 0, 1, 1, 1, 1), (0, 0, 1, 0, 1, 1, 1, 1, 0, 3, 2), (1, 0, 1, 0, 3, 1, 0, 1, 1, 2, 0), (2, 1, 1, 0, 0, 1, 1, 0, 2, 1, 1), (1, 0, 0, 0, 2, 1, 0, 2, 3, 1, 0), (0, 2, 1, 0, 1, 0, 0, 1, 3, 0, 2), (1, 0, 1, 2, 2, 0, 1, 2, 1, 0, 0), (1, 2, 1, 2, 0, 1, 0, 1, 1, 1, 0)]instead of ```py
(0, 0, 1, 0, 2, 1, 1, 1, 1, 1, 2)
(0, 1, 1, 0, 3, 0, 1, 1, 0, 1, 2)
e.t.c.```
@harsh pulsar
Doing print("\n".join(...)) doesn't work either
That prints ```py
[
(
0
,
0
,
1
,
0
,
2
,
1
,
1
,
1
,
1
,
1
,
2
)
#e.t.c.```
you don't need to do str(data), that transforms it into a string, which iterates through it's characters
I do need it?
print("\n".join(data))
TypeError: sequence item 0: expected str instance, tuple found```
lemme rephrase that
you're using it wrong
the problem is that you're casting the whole list to str, when you really want to cast each element to str
for the latter you want to do map(str, data)
print('\n'.join(map(str, data)))``` thanks :~)
def get_results():
data = cursor.execute("""SELECT * FROM results""").fetchall()
print('\n'.join(map(str, data)))
d0 = [x for x in data[0] if x == 0]
d1 = [x for x in data[1] if x == 0]
d2 = [x for x in data[2] if x == 0]
d3 = [x for x in data[3] if x == 0]
d4 = [x for x in data[4] if x == 0]
d5 = [x for x in data[5] if x == 0]
d6 = [x for x in data[6] if x == 0]
d7 = [x for x in data[7] if x == 0]
d8 = [x for x in data[8] if x == 0]
d9 = [x for x in data[9] if x == 0]
print("\n")
print(len(d0))
print(len(d1))
print(len(d3))
print(len(d4))
print(len(d5))
print(len(d6))
print(len(d7))
print(len(d8))
print(len(d9))```Feel like this is still too complicated
ik I can make the print better, but I feel like the d0, d1 e.t.c. is too complicated
each element of data is 1 row
def get_colnames(cursor):
""" Get column names for cursor's result set """
return [coldesc[0] for coldesc in cursor.description]
cursor.execute("""SELECT * FROM results""")
colnames = get_colnames(cursor)
data = [dict(zip(colnames, row)) for row in cursor.fetchall()]
print([row for row in data if row['n0'] == 0])
something like that @hazy mango
let me know if that works for you. i might have made a mistake or a typo
[{'n0': 0, 'n1': 0, 'n2': 1, 'n3': 0, 'n4': 2, 'n5': 1, 'n6': 1, 'n7': 1, 'n8': 1, 'n9': 1, 'n10': 2}, {'n0': 0, 'n1': 1, 'n2': 1, 'n3': 0, 'n4': 3, 'n5': 0, 'n6': 1, 'n7': 1, 'n8': 0, 'n9': 1, 'n10': 2}, {'n0': 0, 'n1': 0, 'n2': 1, 'n3': 0, 'n4': 1, 'n5': 1, 'n6': 1, 'n7': 1, 'n8': 0, 'n9': 3, 'n10': 2}, {'n0': 0, 'n1': 2, 'n2': 1, 'n3': 0, 'n4': 1, 'n5': 0, 'n6': 0, 'n7': 1, 'n8': 3, 'n9': 0, 'n10': 2}]```is the output
I don't think that's right...?
@harsh pulsar
if your columns are named n0..n10, then it is right
but that doesn't give me the info I want
I'm looking for a better way of doing this
Better being shorter
uhhhhhhhhhh
i feel like you're misunderstanding sql
what are n0..10 supposed to represent
n0..n10 is the column names
I want to get all values of each column
If it is 0, then add to {column}fail
Otherwise add to {column}success
i get that they are the column names
This is my table
but what is the data in them supposed to represent
The amount of times a number was generated in 10 attempts
Hence the sum of each row is 10
so the column name represents the number? or the row index represents the number
So n0 means amount of times the number 0 was generated
n1 means amount of times the number 1 was generated
e.t.c.
The row index is how many times the 'test' (generating 10 numbers) has been executed
def saveResults(n0, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10):
cursor.execute("""INSERT INTO results(n0, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10) VALUES (?,?,?,?,?,?,?,?,?,?,?)""", (n0,n1,n2,n3,n4,n5,n6,n7,n8,n9,n10))
db.commit()
def run():
for a in range(10):
n0 = 0
n1 = 0
n2 = 0
n3 = 0
n4 = 0
n5 = 0
n6 = 0
n7 = 0
n8 = 0
n9 = 0
n10 = 0
for i in range(10):
r = random.randint(0, 10)
if r == 0:
n0+=1
elif r == 1:
n1+=1
elif r == 2:
n2+=1
elif r == 3:
n3+=1
elif r == 4:
n4+=1
elif r == 5:
n5+=1
elif r == 6:
n6+=1
elif r == 7:
n7+=1
elif r == 8:
n8+=1
elif r == 9:
n9+=1
elif r == 10:
n10+=1
print(f"0: {n0}\t1: {n1}\t2: {n2}\t3: {n3}\t4: {n4}\t5: {n5}\t6: {n6}\t7: {n7}\t8: {n8}\t9: {n9}\t10: {n10}")
saveResults(n0, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10)```This is the code (might be easier for you to understand from code)
@hazy mango uhh i just gave an example
that isnt the whole thing
yes that is the correct output for part of what you want. that gets you your data, and then the last line filters to show you only rows where n0 == 0. You still need to repeat that filtering process for every condition, but it saves you several round trips to the database.
Yeah I see
I don't really get where I need to go from here though
Wait
I think I got it
Thanks :~)
How to print the amount of rows a database has?
(In my case 10)
@harsh pulsar
if you already have the data just get the length of the list w/ your data in it
if you dont already have it, use a sql query
yeah, I do
Thanks
:~)
def get_colnames(cursor):
""" Get column names for cursor's result set """
return [coldesc[0] for coldesc in cursor.description]
def get_results():
cursor.execute("""SELECT * FROM results""")
colnames = get_colnames(cursor)
data = [dict(zip(colnames, row)) for row in cursor.fetchall()]
num_columns = len(data)
fail0 = len([row for row in data if row['n0'] == 0])
fail1= len([row for row in data if row['n1'] == 0])
fail2= len([row for row in data if row['n2'] == 0])
fail3= len([row for row in data if row['n3'] == 0])
fail4= len([row for row in data if row['n4'] == 0])
fail5= len([row for row in data if row['n5'] == 0])
fail6= len([row for row in data if row['n6'] == 0])
fail7= len([row for row in data if row['n7'] == 0])
fail8= len([row for row in data if row['n8'] == 0])
fail9= len([row for row in data if row['n9'] == 0])
fail10= len([row for row in data if row['n10'] == 0])
success0 = len([row for row in data if row['n0'] != 0])
success1 = len([row for row in data if row['n1'] != 0])
success2 = len([row for row in data if row['n2'] != 0])
success3 = len([row for row in data if row['n3'] != 0])
success4 = len([row for row in data if row['n4'] != 0])
success5 = len([row for row in data if row['n5'] != 0])
success6 = len([row for row in data if row['n6'] != 0])
success7 = len([row for row in data if row['n7'] != 0])
success8 = len([row for row in data if row['n8'] != 0])
success9 = len([row for row in data if row['n9'] != 0])
success10 = len([row for row in data if row['n10'] != 0])
```Anything I can change here to make shorter? @harsh pulsar
eh, depends on what youre trying to do
explicit is better than implicit, as they say
True
@hazy mango
colnames = ['n%i' % i for i in range(10)]
fails = {colname: [row for row in data if data[colname] == 0] for colname in colnames}
successes = # exercise left for the reader
Thanks
Ideas what's failing?
Jan 17 23:32:16 cloud-db-01 postgresql@10-main[1460]: Error: /usr/lib/postgresql/10/bin/pg_ctl /usr/lib/postgresql/10/bin/pg_ctl start -D /var/lib/postgresql/10/main -l /var/log/postgresql/postgresql-10-main.log -s -o -c config_file="/etc/postgresql/10/main/postgresql.conf" exited with status 1:
Jan 17 23:32:16 cloud-db-01 systemd[1]: postgresql@10-main.service: Can't open PID file /var/run/postgresql/10-main.pid (yet?) after start: No such file or directory
Jan 17 23:32:16 cloud-db-01 systemd[1]: postgresql@10-main.service: Failed with result 'protocol'.
Jan 17 23:32:16 cloud-db-01 systemd[1]: Failed to start PostgreSQL Cluster 10-main.
I think it cant find the file?
yeah, it's a bug in Ubuntu.
there should be RuntimeDirectory in the service file
if not you can add that with systemctl edit
fails = {colname: [row for row in data if data[colname] == 0] for colname in colnames}
TypeError: list indices must be integers or slices, not str``` @harsh pulsar error from code you gave me yesterday
you probably want row[colname]
thanks
print(f"No.\t|\tFails\t|\tSuccesses\n"
f"0\t|\t{fail0}\t|\t{success0}\n"
f"1\t|\t{fail1}\t|\t{success1}\n"
f"2\t|\t{fail2}\t|\t{success2}\n"
f"3\t|\t{fail3}\t|\t{success3}\n"
f"4\t|\t{fail4}\t|\t{success4}\n"
f"5\t|\t{fail5}\t|\t{success5}\n")```Is there a better way of doing this? A way of doing this in one line using a list comp or something?
you could either change your approach to storing fails and successes in lists which you can then index in a loop
fails is stored in a list
or you could try locals()[f'fail{n}']
oh ok. well if you put successes in a list then you can do this:
for i in range(5):
print(i, fails[i], '|', successes[i], sep='\t')
Also, I don't like how I'm getting success. py success0 = len([row for row in data if row['n0'] != 0])
That means it treats any amount of successes as 1 success
So I can succeed say 7 times per loop, but it will count that as 1
you could switch that to an any() with just a generator instead of a list
any(True for row in data if row['n0'] != 0)
something like that
I don't think I'm explaining properly.
What I mean is it says here that n0,n1 and n2 succeed 6 times
But n0 succeeded 2+1+1+2+2+1 (9)
And n1 succeeded 1+2+2+2+1+1 (9)
And n2 succeeded 1+1+2+1+1+1 (7)
But because the amount of numbers that != 0 is 6, it says 6 successes
any will return a boolean
do you how many are != 0 or the sum of the non-zero numbers
What I want is the sum of the non-zero numbers, what I have is how many are != 0
ah ok. sum(row). there
oh right it's a dict. sum(row.values())
success0 = sum([row.values() for row in data if row['n0'] != 0])
TypeError: unsupported operand type(s) for +: 'int' and 'dict_values'```
success0 = sum([row for row in data if row['n0'] != 0])
TypeError: unsupported operand type(s) for +: 'int' and 'dict'```
no, just sum(row.values()) by itself.
woah woah woah woah woah
ok in this instance you want something like um, sum of all row['n0'] right?
my understanding is that they want the sum of all non-zero values in a row. and each row is a dict.
that about right?
^
yeah, but i assume each rowdict was like {'n0': 5, 'n1': 1, ...}...?
{'n0': 2, 'n1': 1, 'n2': 1, 'n3': 0, 'n4': 1, 'n5': 1, 'n6': 2, 'n7': 1, 'n8': 0, 'n9': 1, 'n10': 0} {'n0': 0, 'n1': 2, 'n2': 1, 'n3': 3, 'n4': 0, 'n5': 0, 'n6': 1, 'n7': 0, 'n8': 1, 'n9': 1, 'n10': 1} {'n0': 0, 'n1': 0, 'n2': 0, 'n3': 1, 'n4': 3, 'n5': 0, 'n6': 2, 'n7': 1, 'n8': 1, 'n9': 2, 'n10': 0} {'n0': 1, 'n1': 0, 'n2': 2, 'n3': 0, 'n4': 1, 'n5': 0, 'n6': 2, 'n7': 2, 'n8': 1, 'n9': 1, 'n10': 0} {'n0': 1, 'n1': 2, 'n2': 1, 'n3': 3, 'n4': 1, 'n5': 0, 'n6': 0, 'n7': 1, 'n8': 0, 'n9': 0, 'n10': 1} {'n0': 0, 'n1': 2, 'n2': 1, 'n3': 0, 'n4': 0, 'n5': 0, 'n6': 3, 'n7': 0, 'n8': 1, 'n9': 1, 'n10': 2} {'n0': 0, 'n1': 0, 'n2': 0, 'n3': 1, 'n4': 0, 'n5': 1, 'n6': 1, 'n7': 2, 'n8': 3, 'n9': 2, 'n10': 0} {'n0': 2, 'n1': 0, 'n2': 0, 'n3': 1, 'n4': 0, 'n5': 0, 'n6': 2, 'n7': 0, 'n8': 1, 'n9': 1, 'n10': 3} {'n0': 2, 'n1': 1, 'n2': 1, 'n3': 1, 'n4': 0, 'n5': 1, 'n6': 0, 'n7': 4, 'n8': 0, 'n9': 0, 'n10': 0} {'n0': 1, 'n1': 1, 'n2': 0, 'n3': 1, 'n4': 1, 'n5': 2, 'n6': 0, 'n7': 1, 'n8': 0, 'n9': 2, 'n10': 1}```is the value of `data`.
```py
[2, 0, 0, 1, 1, 0, 0, 2, 2, 1]```is the values of `data['n0']`
I think what I want to do is sum(data['n0'])
But that doesn't work because data['n0'] is a list
sum(row['n0'] for row in data). is that what you're looking for? sum of all n0 values in each row?
and so on for n1, n2, etc?
success0 = [sum(row['n0']) for row in data]
TypeError: 'int' object is not iterable```
paranthesis goes on the end, after data
So
Now I've got it printing
[9]
I want it to print just 9
Can I just do like success0[0]?
I don't want it in a list
then remove the square brackets.
you don't need the [] around the sum
Yeah, sorry. I needed it before I moved the ) to the correct position
right, sum is just a function.
See I'm getting so confused over what I need to do here for the next part
This is my table...
Wait, is rows going up+down or left+right?
rows are horizontal, columns are vertical
Ok, so
Each ROW is 10 generations of a random number
Each COLUMN is the number
What I want to do, is find the probability of a number being chosen by the random module by reading from this, but I'm getting really confused with the maths behind it
I think I need to divide each ROW by 10, and then divide the sum of all COLUMNS by the number of COLUMNS?
So chance of getting a 0 would be ((2/10) + (0/10) + (0/10) + (1/10) + (1/10) + (0/10) + (0/10) + (2/10) + (2/10) + (1/10))/10
Which is 0.09, so the probability of a 0 is 0.09
Is that maths right?
that doesn't look right at all to me.
As a percentage it would be 9% (0.09x100)
0.09 means 9 percent. meaning 9 out of every 100. you have 100 numbers in that table and there are more than 9 zeros.
oh i see, n0 represents the number of times the generator generated 0
im not really sure. stats and maths in general isnt my strong suit.
It's not mine either xD
But it seems right
Since, there's 10 possibilities
So the percentage would be about 10% for each number
And 9% is pretty much 10% xD
Yeah, I've done that for all of them
And it adds up to 100 so it must be right
Thanks @gilded narwhal :~)
👍
Hey, weird question incoming since I started with databases some days ago.
is there a way to compare the first number of a BigInt with a variable?
Like the LEFT Function but with a BigInt
print(f"No.\t|\tSuccess\n"
f"0\t|\t{success0}%\n"
f"1\t|\t{success1}%\n"
f"2\t|\t{success2}%\n"
f"3\t|\t{success3}%\n"
f"4\t|\t{success4}%\n"
f"5\t|\t{success5}%\n"
f"6\t|\t{success6}%\n"
f"7\t|\t{success7}%\n"
f"8\t|\t{success8}%\n"
f"9\t|\t{success9}%\n"
f"10\t|\t{success10}%"
)```
The result of the above code is below. How can I change it so that things are better in-line with each other? I thought `\t` would do this, but apparently not
@vestal geyser can you cast to string first? seems silly but possibly the best way
is there a way via sql?
CAST ?
Ah yes perfect, thank you!
Does anyone of you know if there's a async compability library for accessing Microsoft SQL or should I just use http://www.pymssql.org/en/stable/ ?
I had a quick look but I couldn't find anything
you could probably make use of the executors though, if you really needed that
@copper sphinx
Needed what? You mean Microsoft SQL as I think that code would be blocking?
Umm, no.
Main database is done using asyncpg, but I would need to get access to Microsoft SQL too.
okay yes, you're using asyncio
Ah, you meant that okey.
Then yeah, the executor method is probably what you want
Extract whatever you're aiming to do into a bunch of functions
Here's an example of using the executor directly
it's a little convoluted, though
but essentially you factor your database operations out into functions and submit them to an executor
submitting them will give you a Future
and then you should be able to await that Future
Unfortunately, I have no idea how that would actually work.
Well, for lack of a better example, let's say you're a company that sells widgets and you want to put each widget sale into your MSSQL database
so you might have a function that adds each sale to the database, eg
def add_widget(widget_name, widget_amount):
# ...
and in that function you add your row to the database
then later on, you want to do this asynchronously, so you might...
executor = ThreadPoolExecutor()
async def my_function():
await executor.submit(add_widget, "widget a", 4)
Ooh, okey that helped for me to understand it better. :)
note that we pass the function directly to submit, followed by its arguments
instead of calling it ourselves
the executor will do that for you
Yes, I noticed.
That's the approach I'd recommend
Alright, thank you for the help. :)
No problem, good luck \o/
I have a question for this channel myself, as it happens
I'm working on a little finance tracking app to train myself up with Qt, but I'm stuck on data storage - I think I want to go SQLite, but I'm wondering if it's better to store transactions under accounts in one big transactions table, or whether it would be better to have a table per account instead
and if the latter, how I might get that to work with something like peewee
i would create an accounts table and reference the account ID in the transaction entries
But note that sqlite is a bit messy when it comes to fk relationships by default; you need to enable them explicitly for sqlite to validate the constraints
hmm, I wonder if peewee will do that for me
Alright, that's what I was expecting to hear since peewee and other ORMs aren't really designed to deal with dynamic models
Does sqlite actually handle giant tables reasonably well?
Actually I've gotta do some baking now, I'll check back later
for anything that's supposed to handle "giant tables" i wouldn't even bother with sqlite
@ionic pecan The problem is what else you'd want to use though, for local file storage of this type of data
The structure does very much suit sql
well then you don't really have any choice
Hmm, I guess so
Well, thanks
Maybe I should do something like splitting into files per year or something
Go for it, gotta get back to baking
i was told avoid pyodbc because of auth token requirements connecting to my work db
we use ms sql, and (still) on CRM 2011
regardless - i get the error that my sql isnt a valid query
so are there any other alternatives to integrating sql directly or the script file into a py function?
i was told look at py-LINQ
issue is i already have, say, 100+ different sql queries and would just want to call them, read the output into a pandas DF and work from there
"5. List all product names and the value of each product in the warehouse. Rename the calculated attribute as 'ValueInStock'"
This returns only one, and I have no ideas why?
SELECT
ProductName, sum(UnitPrice) as ValueInStock
FROM
products
WHERE
products.UnitsInStock >= 100
@tropic bloom pymssql maybe?
That's what samip there is using
pymssql looks like it uses pyodbc conx as well
or that its a dependancy
i cant really test it as im out of work rn but was enquiring
cursor.execute("""
IF OBJECT_ID('persons', 'U') IS NOT NULL
DROP TABLE persons```
instead of hardcoding sql
cant i just call a script in the directory
Are you asking for a solution that doesn't require you to write SQL?
Because that'll probably need a big restructure
i dont mind copying in the sql
@viral crag Wait, what about me?
I mean yeah if you have some powershell or bash script or something you could just run it
@copper sphinx You were answered
Ah.
..but you likely want an ORM instead of just running scripts
samip try groupby it should work
heres the scenario
im checking one HUGE table
for records marked as 'new'
each SQL script uses different filters for different locations
Agent Rho, thank you. That's what I was missing. :)
which then spits out a list. what i want, is for that list to do into a DF, then write to CSV. rinse and repeat for locations.
so, 1 py doc, 10 SQL queries acted on
i cant even get past the 'not valid sql query' issue
The problem you have is that you need some kind of auth token?
I haven't worked with mssql in yonks, btw
seems so
Can you get that token from the SQL server admin tools?
we need it for our AI priority assignment
i could
but im too new i think they dont like me asking too many questions
my boss told me use LINQ
:/
ill try pymssql
if i can find the error message ill post it
Linq isn't really.. That's a C# thing
py-linq is a port
Yeah but either way you need to connect to the database
eh sorry
im not exactly helping minus hte errors. ill try some other queries tomorrow
i have a sqlite database with a table it has a Int in a row called ids how can i check if 1234 is in that row? so if 1234 is in ids do something
but I don't want to check if the row exists i wanna check if 1234 is in that
You still have to do it with a selection
It depends on the SQL dialect
But I have to wonder what your use-case for this actually is
I wanna check if a id is already in my db
Wym check the whole thing
so you have an ID and a bunch of rows, and you want to find the row with that specific ID?
either I don't understand how they are called or the row is called ID and it's an int
And I Insert many different ids to the row ID where I wanna check if that ID is already in use
The only thing I can tell you from that is that you will have to either run a select query against the table, or iterate over each row that you already have in memory with a for loop
DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
import pymssql
What does people think of this? Should I be using pymssql then?
Is there a way for my bot and my friend's bot to use one database somehow if hosted on different machines?
Yes, it's possible but not recommended. @quasi holly
I recommened having a text file
And reading and writing into it
That can then be posted wherever
wait, why?
Usually databases aren't just a local file
You'd have a database server and connect to that or abstract it away with a webapp
DB browser , you can connect that?
Ideas?
Code:
# Auhtor: Sami "samip5/samip537" Mäntysaari
# Purpose: This file is for storing Microsoft SQL related tasks and queries.
import config
import pyodbc
import asyncio
import concurrent.futures
mssql_host = config.mssql_host
mssql_database = config.mssql_database
mssql_user = config.mssql_user
mssql_pass = config.mssql_password
driver = '{ODBC Driver 17 for SQL Server}'
def get_stats(user_id):
cnxn = pyodbc.connect(
'DRIVER={ODBC Driver 17 for SQL Server};SERVER=' + mssql_host + ';DATABASE=' + mssql_database + ';UID=' + mssql_user + ';PWD=' + mssql_pass)
cursor = cnxn.cursor()
cursor.fetch("""
select count(*) cnt from discord_messages dm
inner join discord_channels dc on dm.channel_id = dc.channel_id
where [user_id] = $1
""", user_id)
return cnxn.commit()
async def get_stats_executor(user_id):
loop = asyncio.get_running_loop()
with concurrent.futures.ThreadPoolExecutor() as pool:
result = await loop.run_in_executor(pool, get_stats(user_id))
return result
Traceback:
Traceback (most recent call last):
File "Z:\Varasto\Programming\Python\Parempi-Bot\venv\lib\site-packages\discord\ext\commands\core.py", line 62, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Sami\Documents\Parempi-Bot\cogs\profile.py", line 14, in dev
await mssql_db.get_stats_executor(user_id)
File "C:\Users\Sami\Documents\Parempi-Bot\cogs\utils\mssql_db.py", line 31, in get_stats_executor
result = await loop.run_in_executor(pool, get_stats(user_id))
File "C:\Users\Sami\Documents\Parempi-Bot\cogs\utils\mssql_db.py", line 18, in get_stats
'DRIVER={ODBC Driver 17 for SQL Server};SERVER=' + mssql_host + ';DATABASE=' + mssql_database + ';UID=' + mssql_user + ';PWD=' + mssql_pass)
pyodbc.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
Or what could be a problem with using pymssql:
Traceback (most recent call last):
File "src\pymssql.pyx", line 636, in pymssql.connect
File "src\_mssql.pyx", line 1957, in _mssql.connect
File "src\_mssql.pyx", line 676, in _mssql.MSSQLConnection.__init__
File "src\_mssql.pyx", line 1683, in _mssql.maybe_raise_MSSQLDatabaseException
_mssql.MSSQLDatabaseException: (20002, b'DB-Lib error message 20002, severity 9:\nAdaptive Server connection failed (<censored>.database.windows.net:1433)\n')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "Z:\Varasto\Programming\Python\Parempi-Bot\venv\lib\site-packages\discord\ext\commands\core.py", line 62, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Sami\Documents\Parempi-Bot\cogs\profile.py", line 14, in dev
await mssql_db.get_stats_executor(user_id)
File "C:\Users\Sami\Documents\Parempi-Bot\cogs\utils\mssql_db.py", line 29, in get_stats_executor
result = await loop.run_in_executor(pool, get_stats(user_id))
File "C:\Users\Sami\Documents\Parempi-Bot\cogs\utils\mssql_db.py", line 16, in get_stats
conn = pymssql.connect(mssql_host, mssql_user, mssql_pass,mssql_database)
File "src\pymssql.pyx", line 642, in pymssql.connect
pymssql.OperationalError: (20002, b'DB-Lib error message 20002, severity 9:\nAdaptive Server connection failed (<censored>.database.windows.net:1433)\n')
Right i have a slight issue
I have an embed message and it prints but it shows the link to the photo
Is there a way i could stop that?
Takes the photo from Database
Hi, i'm using pymongo and have some questions about it, if I insert a document into the database, then later add another key and value into the data i'm inserting, would it update the existing documents with the key and value? I know it's possible in NodeJS with mongoose
Good stuff
Although I do get a collections.abc error
Traceback?
Using or importing the ABCs from 'collections' is depreciated
I can't copy it off my work machine
But that's the jist
It's telling you that the approach you're using is no longer supported and may be removed in a later version
Yup
I'm scared of it 🤣
Even if I put from collections.abc import iterable it pops up
🤔
Probably because it's in a different module now, likely just abc
https://pokemondb.net/pokedex/all
is there a way i can iterate all through these and put it all into a db/
yes
Could u explain how i would go around it?
Only problem is that the Pokemon Database isn't actually something you can pull from.
In general, no. All written content, site design and data display/layouts have had a huge amount of research and effort put into them to make as easy to read as possible. Do not steal our content!```
Instead, they attempt to redirect you either the PokeAPI (https://pokeapi.co/) or the Veekun Pokedex (https://github.com/veekun/pokedex) for your scraping needs.
herse a pymssql question
instead of `cursor.execute("""SQL QUERY HERE""")
can i not call a class
Not from there, no, since they kinda forbid it.
However, the Veekun github is looking kinda promising, or if you're into REST APIs, I've worked a tiny bit with PokeAPI.
havent Worked with like anything par discordpy and databases
A mini-encyclopedia of Pokémon species, types, evolutions, and moves.
Much easier
An open RESTful API for Pokémon data
That's mad
@viral crag its @tropic bloom but on my work account lol
would you see any problems with this
df_MDIV = pd.read_sql(OL_MDIV, conn)
OL_MDIV = FreshOL + MenaDIV
MDIV_list = list()
for x in range(len(df_MDIV.index)):
MDIV_list.append('A1')
MDIV2 = pd.DataFrame()
MDIV2['HC3']=MDIV_list
frames_MDIV_Fresh_OL = [df_MDIV, MDIV2]
MDIV_Fresh_OL = pd.concat(frames_MDIV_Fresh_OL, axis=1)
print('MDIV_Fresh_OL = ' + str(df_MDIV.shape[0]))
MDIV_Fresh_OL.to_csv('MDIV_Fresh_OL.csv', encoding='utf-8', index=False)```
where the SQL is literally a string = in this case, OL_MDIV
Nothing immediately obvious, but these variable names are incredibly hard to read
I am aware
theres going to be upwards of 30 at least
any way I can possibly add in class/functions to this, or not really given the amount of variables
im starting to learn POSTGRESQL and is there a good tutoral for learning how it works
with python
Is there a way to remove port binds from docker? I installed influxdb and need to remove before reinstalling it, however it can't be created because a port is in use. I tried several commands to list ports, but the container is gone and no ports are showing up. Is there any good documentation about docker ports?
The bind is on tcp 0.0.0.0:8086
That's a #414737889352744971 question, but you probably need to remove the network docker crated for that container
I removed it and the only running container is not related.
You may also consider docker prune -af which will remove all non-running containers and images
Finally, make sure something else on your system isn't using that port
I have 2 established connections using localhost:8086 for tcp6
Are they listening?
Established
Then I have no idea
Thanks for helping though
I may just start over
I got it by running:
netstat -ltnp | grep -w ':8086'
kill -9 [PID]
Where PID is from the first command
@gray lodge you do docker image prune, docker container prune and docker network prune. if the containers are not running they shouldnt be blocking the ports unless a docker network is active, and docker network list following by inspecting any networks should take care of that
ive never really seen issues before with ports still being blocked without the containers running, so something somewhere is using them
i personally tend to bind containers to nondefault host ports so i never block a non-container instance of an application or confuse myself
Thank you for that information. I am still new to this, but this should help me learn docker.
for websites, would you ever need anything else than sqlite unless you are planning to make a big website?
@quiet ermine so the fundamental problem with sqlite is that it's file-based. it's a single file.
this means you can't share it between multiple app/server instances, it can't be accessed by multiple clients at once, it is not a server, etc
so generally speaking, sqlite is great during dev, but you almost never want it in production.
that said, chances are you are using an ORM or some database library that can switch between sql dialects easily
lots of people use sqlite for local dev but postgres in production
which db libs and ORMs can usually handle nicely as long as you arent using custom stuff that is specific to one of those db systems
so you can absolutely run a "big" site with sqlite, but you couldnt distribute the app. and that is a fundamental aspect of modern apps tehse days
there is the rqlite project, which is a distributed sqlite server, and for a couple years ive been curious to use it, but ive only just lightly played around with it: https://github.com/rqlite/rqlite
uses raft for consensus
but to be honest, you probably want to be running postgres in production. use sqlite locally if you want. or postgres in a docker container you dont have to deal with
i totally understand the ease factor that comes with sqlite but the same general peace of mind can be achieve with real databases if you use containers or managed db instances, etc
Umm, how well does people know sqlalchemy here? I'm trying to build a API for my database, but I'm not entirely sure how I should reference my tables.
Okey, I fixed that problem, but now I'm hitting my head to a wall as I'm unable to figure out how I filter the results so I only get what I want, like use WHERE, but with SQLalchemy.
👌 @ornate isle I'll use SQLite for testing and probably a bit of production (for very small projects, will probably be the first ones I properly do)
Use DATABASENAME
Select a b c
From TABLENAME
Where (filter on a) and (filter on b) and (getdate()-14 on c)
Order by a c b
@copper sphinx that's a general SQL query
Oracle, mssql etc all use the same structure
Ish
Umm, that was not my question.
Not exactly as I meant it as how do I use it with SQLalcemy.
If I have this
from flask import request
from flask_restful import Resource
from model import db, Messages, MessagesSchema
messages_schema = MessagesSchema(many=True)
message_schema = MessagesSchema()
class MessageResource(Resource):
def get(self):
messages = Messages.query.all()
messages = messages_schema.dump(messages).data
return {'status': 'success', 'data': messages}, 200
Where would I put the filter?
Ah, I see.
It should be possible yes.
I have a question, if someone could direct me to the right place, can I execute the full query directly with SQLAlchemy and if yes, how do I do so with using the db.model approach?
You're asking whether you an execute an SQL query directly with SQLAlchemy?
The point of SQLA is that you don't have to write SQL
That also gives you the advantage of being able to support multiple database types with minimal code changes
You should look into the way SQLA does query building, and make use of that
So what would be the correct way to do this then?
select count(*) cnt from discord_messages dm
inner join discord_channels dc on dm.channel_id = dc.channel_id
where [user_id] = '130685606345965568'
As I'm pretty much aware how I should do it with normal SQL queries, but not with SQLA.
It's a columm in my database.
session.query(Message.id).where(Message.user_id == "whatever").join(Channel, Channel.id == Message.id).count()
something like this I think
is this for a Discord bot?
No, the database is from discord data though.
Ah okay
This is for a API for the said database.
more info on the query API: https://docs.sqlalchemy.org/en/latest/orm/query.html
I checked the documentation out, but I'm stuck with understanding how I should do this as I'm currently using it like this:
messages_schema = MessagesSchema(many=True)
message_schema = MessagesSchema()
class MessageResource(Resource):
def get(self):
value = request.args.get('user_id')
if value is not None:
messages = Messages.query.filter(f'discord_messages.user_id = {value}')
messages = messages_schema.dump(messages).data
return {'status': 'success', 'data': messages}, 200
else:
messages = Messages.query.all()
messages = message_schema.dump(messages).data
return {'status': 'success', 'data': messages}, 200
f'discord_messages.user_id = {value}' well this is definitely not right
Well, that part still does work.
Oh, wow, so I'm overcomplicating things.
You should read over the page I linked you
or at least ctrl+f for the things you're trying to do
I have done so already.
That
messages = Messages.query(Messages.message_id).where(Messages.user_id == value)\
.join(Messages.Channel, Messages.Channel.id == Messages.message_id).count()
Gives me an error like TypeError: 'BaseQuery' object is not callable.
Since you're querying the model directly, you don't need the Messages.message_id
in the query call
and I think count might work differently..
although
what is this join about?
you're doing a count of messages
so do you even need the join?
Might be unnecessary at this point.
Probably what you need is more like
session.query(func.count(Messages.message_id)).where(Messages.user_id == value)
I don't have anything imported which that session comes off of..
that's an SQLalchemy session
Which is not imported.
from flask import request
from flask_restful import Resource
from model import db, Messages, MessagesSchema
from sqlalchemy import func
yes, you have to make them
# application starts
Session = sessionmaker()
# ... later
engine = create_engine('sqlite:///foo.db')
Session.configure(bind=engine)
sess = Session()
You can put that somewhere importable
generally you do want to be using sessions
they allow you to make use of transactions
transactions basically are like, sets of changes and queries
if you have an exception mid-transaction, the entire transaction should be rolled back to preserve your data's integrity
I think that correct documentation would be http://flask-sqlalchemy.pocoo.org/2.3/
You're still using base sqlalchemy under that, but there might be a session in there somewhere, sure
db.session
yep
Yep, so it's already there but "hidden" ish.
Well either way, you have access to it
Yup.
AttributeError: 'BaseQuery' object has no attribute 'where' :(
messages = db.session.query(func.count(Messages.message_id)).where(Messages.user_id == value)
That does not work like it should though.
2019-01-21 16:50:46,859 INFO sqlalchemy.engine.base.Engine SELECT count(discord_messages.message_id) AS count_1
FROM discord_messages
WHERE discord_messages.user_id = %(user_id_1)s
2019-01-21 16:50:46,859 INFO sqlalchemy.engine.base.Engine {'user_id_1': '222394927978381312'}```
I mean, I did ask if what you wanted was the count of matching messages
That's why we removed the join
so that does look correct
So it needs the join apperently.
Are you getting an incorrect count?
I'm not getting any count.
Are you actually doing anything with the return value of that call?
messages = db.session.query(func.count(Messages.message_id)).filter(Messages.user_id == value)
messages = messages_schema.dump(messages).data
return {'status': 'success', 'data': messages}, 200
This should return the count, right?
Not sure what this line is for messages = messages_schema.dump(messages).data
I don't think you need it if what you want is the count
considering messages should just be a number at that point
If I take that out, it errors with typerror.
TypeError: Object of type BaseQuery is not JSON serializable
okay, well why don't you print that and see what it is
Ah right, yeah, you need to add a specifier like .first() I think
It spits out
SELECT count(discord_messages.message_id) AS count_1
FROM discord_messages
WHERE discord_messages.user_id = %(user_id_1)s
in this case you probably want .one()
at the end
that will return exactly one result, or raise an exception
Yes, that works with one().
Good good
it's been a while since I've used SQLA to be honest
got most of that from skimming the first link
But thank you for the help. :)
No problem
I have been hitting my head to a wall already for some time.
this is my table for all users -
def user(c):
first text,
last text,
username text,
password text,
dob date,
email text,
type text,
pic text
)""")``` and i also have a table for those whose types are "Student" which is def student(c):
```c.execute("""CREATE TABLE student (
username text,
yeargroup integer
)""")```
i was wondering how i would merge the 2 together while keeping all the other users who are not type: Student . Thanks in advance 😃
Generally, you wouldn't merge them
However in this case all you would do is put those fields into the first table
and let them be nullable
you already have a type field
class CountMessagesByChannel(Resource):
def get(self):
value = request.args.get('user_id')
if value is not None:
count = db.session.query(func.count(Messages.message_id, Channels.channel_name).where(Messages.user_id == value)
.join(Channels.channel_id == Messages.channel_id)).one()
return {'status': 'success', 'data': count}, 200
else:
return {'status': 'failed', 'data': 'This is not how it works'}, 400
What am I doing wrong now?
TypeError: __init__() takes from 1 to 2 positional arguments but 3 were given
Full traceback required
Traceback at: https://paste.pythondiscord.com/qahicihuci.py
Too many arguments to func.count
So how would I transform this query to SQLA?
select count(*) cnt, channel_name from discord_messages dm
inner join discord_channels dc on dm.channel_id = dc.channel_id
where [user_id] = '130685606345965568'
group by channel_name
you actually appear to be missing a closed paren
well you just need two counts
you have db.session.query(func.count(Messages.message_id, Channels.channel_name).where(Messages.user_id == value).join(Channels.channel_id == Messages.channel_id)).one()
what you probably want is db.session.query(func.count(Messages.message_id), func.count(Channels.channel_name)).where(Messages.user_id == value).join(Channels.channel_id == Messages.channel_id).one()
but your formatting makes this confusing
you've got way too much on a single line
so,
we need to split
Ah, so I can't do with one func.count.
let's format this better
you have ```py
db.session.query(
func.count(Messages.message_id, Channels.channel_name)
.where(Messages.user_id == value)
.join(Channels.channel_id == Messages.channel_id)
).one()
there are two problems with this
firstly, you tried to combine two parameters in func.count
secondly, you're doing the whole thing inside db.session.query
Which is a bad thing?
well yes, it's incorrect
So if not inside db.session.query, then how?
after it
db.session.query(
func.count(Messages.message_id), func.count(Channels.channel_name)
).where(
Messages.user_id == value
).join(
Channels.channel_id == Messages.channel_id
).one()
Oh, wow.
that's one possible way of formatting it
here's another one
(db.session.query(func.count(Messages.message_id), func.count(Channels.channel_name))
.where(Messages.user_id == value)
.join(Channels.channel_id == Messages.channel_id)
.one())
You get the idea
Interestingly enough, there's still no .where. :/
Probably, and also my query is apperently not working as it spits out AttributeError: Neither 'BinaryExpression' object nor 'Comparator' object has an attribute 'selectable'.
that's not a full traceback
that'll be the join
and, indeed
it is
(db.session.query(func.count(Messages.message_id), func.count(Channels.channel_name))
.join(Channels)
.filter(Channels.channel_id == Messages.channel_id, Messages.user_id == value)
.one())
So you join on a table rather than an expression
and then filter by your join condition
Oh, now that gave me much better error.
Oh? :P
sqlalchemy.exc.InvalidRequestError: Could not find a FROM clause to join from. Tried joining to <class 'model.Channels'>, but got: Can't find any foreign key relationships between 'discord_messages' and 'discord_channels'. I had forgotton to include a PK. Darng
whoops :P
Indeed, no wonder it wouldn't work.
Ok so i have a semi decent bot for discord
I wanna make it so each server has its own database
Or table?
Why nuut 😭😭
That's poor database design and will ultimately result in slowdowns and hard-to-manage schema
That's not what I said.
Servers have IDs, you know
No reason you can't have a server_id column and filter on it
I know i was joking 😅 , and i know but how would i go around having 800 pokemon for each server?
Actually yeah that could be good
I'm not really sure what your modus operandi is here, but assuming you have a set of pretedermined pokemon
you have a pokemon table with all of those in there, as well as an ID primary key that's generated for them
and then your "catches" are in a different table
referring to those pokemon only by ID
I have every pokemon , rank and if theyre owned by the user
So for each server id have to create 800 pokemon
yes, I know
From another server
that doesn't contradict what I said
hold on, I'm going to have to draw this for you, aren't I
Ok yeah im understanding now
if a pokemon isn't owned, then it won't be in the catches table for that server ID
Makes alot of sense
you don't need a flag for it in that case.
So if pokemon is in catches with the server id that theyre in, then it will come up its owned by the user id and cant be claimed again
that's the idea
You'll also want to look into joins so you can get data from both tables at the same time
Yeah would be easier than extracting it
Ill have a look at it, tysm 😃
Much harder to do than it looks 😂🙈 (Making a discord bot with databases)
I'd suggest an ORM but that's not something you really want in a Discord bot
Okey, I'm hitting my head to brick with this again. I checked that my query now works directly in the database, so why won't it in my SQLA?
Query for reference:
select count(*) cnt, channel_name from discord_messages dm
inner join discord_channels dc on dm.channel_id = dc.channel_id
where user_id = '380865985479049216'
group by channel_name
well do you have any relationship()s in your models?
Umm, no.
well that'll be it then
look harder :P
Don't skim
You should be looking at https://docs.sqlalchemy.org/en/latest/orm/relationships.html
yes, it's a lot of reading unfortunately
it's an important concept though
channel_name = relationship("Channels", uselist=False, back_populates="discord_messages") This is annoying.
Still the same error.
Maybe a fresh night sleep will help, I hope.
what database do you recommend for min first database that I want to learn I know little of mongo db continuous in it or will I go to another databa?
A normal sql db to play around with?
sqlite is already shipped with your python installation so you could easily use that, if you want sql based
I am a sql guy, so correct me if I am wrong, but I have the impression that NoSQL databases are easier to learn.
They have their own merits and problems
Because they use expressive languages though, the drivers emulate the query language
So it's more or less the same regardless of what language you're actually using
are the merits and problems related to how they work or how easy it is to learn?
when i did my database course at uni half the class was struggling with the whole sql concept
there is also a strong bias from my part here since I only work with sql
Really it depends what kind of person you are
If you hate declarative query languages or you prefer working with stuff like map and reduce then nosql can be quite nice
I have never thought about it in that way.. i like that..
Nosql is often just enterprise map and reduce :P
The satisfaction of writing a complex sql query is still fun though
yeah it totally is..
I don't enjoy it
I do c:
I hate writing sql
But that's why we have ORMs
Probably yeah
let me show you something
Rethinkdb is a bitch
It was amusing that I had to write an API wrapper around the already rich and object-oriented driver
That's a neat query 
You can keep it
You write columns and what not in norwegian (!?)
My queries are not even close to that :P
SELECT id, money FROM users
WHERE guild_id = $1
ORDER BY money desc
limit $2;``` 😎
but then again my dbs are hobby level and not very complicated or big.
this is an enterprise level databased, at the moment it has around 50gb of entries
Yeah, mine has ... 1000 entries?
actually 35,000. Forgot it got approved by discordbot list and just yoinked the entire userlist there
can any one help me in.....How to create setup.py file that will contain all dependancy of my project...?? i am using flask
@stray night I don't think this question really fits this channel. Also, please refrain from asking your question in multiple channels simultaneously, as that defeats the purpose of having multiple channels.
@stray night have the setup.py file run pip to install your requirements.txt file
anyone have experience with sqlalchemy as it pertains to connecting to existing tables? Using pyodbc I can run a table query no problem but with SQLalchemy it can't even find the table at all
@vocal oxide They've received help in one of the other channels they've asked their question in.
can anyone help with a script im trying to make that involves two excel sheets and some python?
yes, but im not sure what that has to do with databases
Guessing he feels like EXCEL would class as the database
I wouldnt class it as
Im not experienced transfering from excel so ill try look it up for u
ohh you dont have to go through that trouble... that's what i;m doing hehe
https://www.sitepoint.com/using-python-parse-spreadsheet-data/ might be good 😃
No problem , enjoy
aha yeah i have the same problem
excel sheet -> export to csv -> import dicts with csvkit or similar
When people make GUI programs in Python that need database access, do they usually open a new db connection every time they write something? Or do they keep the connection around for whenever it's needed?
with a Real Database, you can generally do a connection pool to let you write the code as if it opens a new db connection each time, without the cost of actually making and closing connections
with sqlite3 it probably doesn't matter much either way
@fluid nova have a look at pandas
I currently use it to read into SQL, then append and write to csv
@vocal oxide do you check the sql connection string here you need to provid servername,tablename,usernameand password so it will connect to particular table..
Thanks to the folks here I was able to fix some bugs and v1 of our scraper is going live on our company's AWS servers
❤️
anyone versed in sqlalchemy?
Sqlalchemy has properties you can declare on classes (example using flask sqlalchemy)
class User(db.Model):
first_name = db.Column(db.String(26))
last_name = db.Column(db.String(26))
is_real == db.Column(db.Integer)
@property
real_user(self):
return self.is_real == 1
but if you query that property
db.session.query(User).filter(User.real_user == True).all()
you get nothing because full_name is a property not any sort of sql expression.
e.g. <type 'property'>
question is there a way to disable that so it throws an error so people can't query of property. Seems like it should be a built in behavior because hybrid_properties are querably but regular properties aren't.
is apache cassandra good
that sounds familiar
the nosql db?
its god
*good
can i also suggest looking into aerospike if you're going to use it for anything big
oh ok
i've never heard of aerospike, will look into it
actually, i just realized that discord uses apache cassandra
i was going to use it for storing passwords on my website
@viral crag want to see the variable nightmare im facing
Ideas?
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not create SSL context: library has no ciphers ?
Hi, guys. Do you have any link to Python ETL best practices?
mycursor.execute("SELECT amount, serial, name FROM produkter_product WHERE serial = '{0}'".format(identification))
I'm trying to grab some data from MySQL database
but its case sensitive
and i'd like to get the result from both FAR and far
nvm fixed it
If I want to have multiple bots accessing one db, which db should I use? I am currently using SQLite but that isn't good for multiple hosts
Postgresql
I need psycopg2 to control it, right?
You probably want asyncpg
Alright install postgre now and will look into asyncpg
Hey all, using MySQL and python and trying to change a column in my database without having to redo the whole thing. basically the users did a weird and made their dates in mmddyy format and I want to change it to yyyymmdd format.
I believe that the way I had it set up (I tried to use slicing) was changing the variable I was using, so then I couldn't get the day and year parts once I slicing the variable for the month. 😦
I'm not sure how this is working under the hood but based on my print statements, that is is my guess. Is there a way for me to set this up so that I don't change the original variable in trying to pull out this information?
and bigger picture: is there a better method than slicing because another issue I'm having is...
well to get all the problematic fields, I'm using fetchone or fetchall and that gives me a tuple or tuple of tuples and I can't turn a tuple into an integer to add 2000 to it. maybe instead I try to turn it into a string and then concat str(20) + yy...
@quasi holly are the bots written in async code? if not, you dont need asyncpg. and probably dont want it. you want a connection pool
The PostgreSQL documentation specifies that logical and streaming replication can both be enabled concurrently. However, it is not possible to create a publication on logical replication from the master on the slave when streaming replication is enabled, since the slave is set to read-only mode, and CREATE SUBSCRIPTION cannot be used inside read-only transactions. How is this meant, that the master can replicate both via streaming replication and logical replication at the same time?
Hi guys, I'm writing a web scraper for real estate websites and I was wondering, what is better to do when an estate is offered with a phone number or email but the name of the person or agency is missing... Would you advice to store this missing information as an empty string or "anononymous" would be better? Thanks
store it as null
as in leave it blank
when you go to update a row itll cause less issues
not that it matters at all but yeh
What's the quickest database when it comes to storing loads of data and retrieving that data?
Haha, it's never quite that simple
And when I say loads I mean over a million items
Postgresql is the database we mostly recommend to people
MariaDB is also quite capable
I'm currently using sqlite so is postresql quicker?
Sqlite is kind of unsuitable for a lot of large applications
yeah, I've found that
The others require you to run and connect to a database server
It's totally worth it though
Then I'll probs use postgresql
Is there any websites that have a good introduction to it? @viral crag
I don't know off the top of my head, but some libraries you can use include psycopg2 and asyncpg
👌
How to create a host on your own PC? @viral crag
I tried doing localhost but that raises an error
What kind of error are you coming up with?
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: could not connect to server: Connection refused (0x0000274D/10061)
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused (0x0000274D/10061)
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?```
Yrp
I ran the installer and it's now installing Microsoft Visual C++ 2013 Redistributable (x86) - 12.0.40660???
And a load of other stuff as well - guess they're requirements?
@viral crag
Yes they are
Ah, ok
Guess I gotta play the waiting game 😦
@viral crag Stack Builder has come up with a load of options saying what do I want to install - what needs to be installed?
@tropic zealot
I'm on the part after that
I'd show a screenshot but my screenshot software isn't working
I've got loads of click-downs Add-ons, tools and utilities Database Drivers Database Server Registration-required and trial products Replication Solutions Spatial Extensions Web Development
Says I have to install at least one thing
I think pgadmin is in the first one
I'm on the page after that
Also, the database server
In database server it shows a load of versions and then one version with (installed) next to it
Then you're good, just close that
There should be something in your start menu, otherwise go to the services section in your control panel and start it there
Don't know what you're talking about...
Nothing in start menu and idk what you mean by services section in your control panel
wait, I think I got it
I'm getting really confused... I thought this would be easy but apparently not
All I want to do is convert sqlite to postgresql
Think I might just leave it because this is too confusing
Hello o/
Sweet
I'm making a application which requires a bulk upsert, However mid upsert it throws erros at me.
i need help on databases
@queen gull maybe show us what you need first?
you were just in the same channel as me...
i want to put the content of a message into the database
they said
it needs another column
I dont really get what I'm supposed to do
:/ so basically I need to do all the work 😦
paste is your friend
@bot.command()
async def setuid(ctx, *, words):
author_id = str(ctx.message.author.id)
await bot.pg_con.fetch("SELECT * FROM users WHERE user_id = $1", author_id)
await bot.pg_con.execute("UPDATE users SET user_id = words", author_id)
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UndefinedColumnError: column "words" does not exist
Yes I see
Show me how you created database
and how you manipulated it
(added columns)
Welp this is the problem await bot.pg_con.execute("UPDATE users SET user_id = words", author_id)
yeah
I dont really know
how to make the words
or the message content
In the database
i also tried this
await bot.pg_con.execute("INSERT INTO users (user_id) VALUES (words)", author_id)
that didnt work either
huh
i saw a message flash
I was trying to install RethinkDb on a fresh debian instance(from google cloud) which has around 1.7gb memory and 10gb storage. Everything till configure went great but i got this error while running the make command!
@queen gull what is your database schema? it's not clear what words is for.
you probably want something like py await bot.pg_con.execute("INSERT INTO users(user_id, words) VALUES($1, $2)", author_id, words) or ```py
await bot.pg_con.execute("UPDATE users SET words=$2 WHERE user_id=$1", author_id, words)
if you only have one column i'm not sure how you intend to associate the text with the author id
@hearty iron why not use the rethinkdb packages
What is it @ionic pecan?
I tried the first one too but that said package not found. I got a solution for it thougj
wget https://github.com/srh/rethinkdb/releases/download/v2.3.6.srh.1/rethinkdb_2.3.6.srh.1.0stretch_amd64.deb && sudo dpkg -i rethinkdb_2.3.6.srh.1.0stretch_amd64.deb
if you're missing something do sudo apt-get install -f
It worked^^
A={'Jeju': 0, 'Pangyo': 1, 'Seoul': 2, 'NewYork': 3, 'LA': 4}
I have a number (for example 3)
and I'd like to pop the items from A(for example A={'Jeju': 0, 'Pangyo': 1, 'Seoul': 2, 'LA': 4}
Is this db related?
No
None the less use dict.pop(key, default)
for small websites, why not use SQLite?
What if you need to scale it up?
like the website would only ever be small, upto 10k visits per day
you could just use sqlite's native transfer option that can do to something like postgres
What is wrong with my syntax?
"SELET * FROM blacklist WHERE word = %s OR author = %s;"
(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELET * FROM blacklist WHERE word = 'fuck' OR author = 293555442670370817' at line 1")
happens :P
Thankss
LIKE is for pattern matching, = is fine for exact matches
Ah right
Again I need help :')
C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\aiomysql\cursors.py:456: Warning: Truncated incorrect DOUBLE value: '39-80690'
I know it's because I'm comparing the same value twice but I need to
sql_query = "SELECT * FROM reports WHERE case_number = %s OR agency_qir = %s;"
await crsr.execute(sql_query, (id, id))
No, a double is a decimal number
The value you gave is an invalid decimal so it gets shortened
asyncpg's fetch will eat up memory like crazy ar am I mistaken?
It shouldn't by itself afaik
How much are you fetching, and what are you doing with the data
Most of the database code is in that cog.
Cant go indepth with just a phone. Couldn't see anything that stood out other than that youre doing a lot of repedetive queries and keeping connections open for a while for a lot of them
Maybe you could restructure the db in a way so that you could fetch all those values with one query?
Also noticed you used fetch for update statements, those should probably be executes
I have no idea how I would parse the output if it would be from one query.
Could someone help me out here with the memory problem?
what are some usecases for nosql?
SQL: How complicated is it to insert a column of integers that are ordered based on another column in the same table being ordered ascending?
im currently wondering if i should use a databse for my discord bot, and im wondering what database should i use. i know sqlite3 is already built in to python, but i was wondering if there are others which are better, more secure, or any other reason
any recommendations for databases to use?
just stick with sqlite for it
unless its getting a billion pings per day, its stable
(also easier to setup & even though sqlite isnt as secure as some other, larger things, the user will never have direct acess to the database, only through a couple of bot commands)
okay, i'll stick to sqlite3 then
sql_query = "INSERT INTO rooms (uid, name, date, plot, recommendations, note, advertising, id-1, id-2, author, created, url) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);" what's wrong with my syntax?
ERROR:(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-1, id-2, author, created, url) VALUES (245, 'yes', 'off', 'I'M DONE WIT' at line 1")
Please help :'''D
Nvm, id-1 is not a valid name I think
- is minus, so yeah, you are correct.
Does anybody know if there's a way to insert a row into an sqlite database and have some of values filled in with the tables default values and the other values user-supplied?
Although based on what I've gathered from various tutorials and the sqlite docs, it seems to be all or nothing for default values.
If you know what the default value is you can just pass that in?
One sec
Look at how I create the table and then how add_login() works https://repl.it/@ScottRobinson1/SQLite3-Login-V1
(I think this is what you're after)
You just pass in a NULL and it uses the default instead?
I'll find out the fun way in five seconds
Yeah I think so
That seems to not work, I'll just put the defaults into the code instead.
Yeah, sorry. Perhaps try using ? in the format part (where I have username, password...)
I think it uses default when you dont specify the column
^
Db columns - A B C
Insert into db(A B) values (2, 5)```
When I don't specify the columns,it expects data for all solumns, regardless of whether there's a default value or not
but if I specify the column then I only need data for the specified columns
And have C default to something
If that doesn't work I'm blank
It does work lol
Neat
Thanks @hazy mango!
Np 😃
:p
Why has python made changing to my copy variable/list/dictionary affects the original one?
The following channels look free:
**1. #help-falafel inactive for 2h49m21s
-
#help-coconut inactive for 1h31m3s
-
#help-kiwi inactive for 1h15m30s
-
#help-croissant inactive for 20m30s
**
These channels aren't guaranteed to be free, so use your best judgement and check for yourself.
sorry.
The following channels look free:
**1. #help-chestnut inactive for 44m12s
-
#help-falafel inactive for 38m6s
-
#help-kiwi inactive for 25m58s
-
#help-croissant inactive for 22m22s
-
#help-grapes inactive for 19m44s
**
These channels aren't guaranteed to be free, so use your best judgement and check for yourself.
c.execute("""CREATE TABLE :tablename (
username text,
predictedgrade varchar(2),
cag varchar(2));""",
{"tablename":self.currentClass.id})
this gives me the error
Traceback (most recent call last):
File "E:\School-Database\main.py", line 778, in create_
{"tablename":self.currentClass.id})
sqlite3.OperationalError: near ":tablename": syntax error
even though if i do a print(self.currentClass.id) the line before it returns a string ie. "Table1"
you cant substitute tablenames like that
param substitution usually only works on values
ok is there a way i can substitute a variable in for it? @ionic pecan
you shouldnt dynamically create database tables generally
what are you trying to accomplish
ive worked around it now - but everytime a user created a class i was hoping to create a separate table designated to that lesson that would store grades etc for each student
hi
I have two questions
what is a columnar storage.. can someone brief me with an example
and.. why are csv, avro,json considered alternative data sources
hey guys, this is an sqlalchemy as well as a more general db and ORM question, so say I have: people (pkey int id, name) companies (pkey int id, name) employees (int person_id, int company_id, salary, pkey (person_id, company_id))so the employees is it's own model as well as many-to-many secondary table for people and companies. Would you suggest in this case to keep using composite key (the assumption that my models have singular keys makes many things easier in code) or add a surrogate key (either autoincrement or based on person_id, company_id)?
how do i drop my index from a pandas dataframe im concating a bunch of dataframes to excel and i get random index when i print the dataframe to excel
nvm
i needed to have drop=True
Is it possible to have a tree like structure (like nested dictionaries) saved in a database?