#databases
1 messages · Page 88 of 1
@solid void Do you have any idea why it so slow?
I have tried connection to mongodb cloud from my computer, and from heroku cloud (which was a little faster, but not significantly)
ive got a snakes and ladders game - and ive got 2 tables players and game - players has a FK for the gameID - and I want to have a winner column in game that is a FK for playerID - is this acceptable or is there a better way to do it?
@pale oriole try
%sinstead of?
@celest blaze works Thanks!
@obsidian leaf check out database normalization for some good strategies on PK, FK organization.
heres a good starting point: https://www.essentialsql.com/get-ready-to-learn-sql-11-database-third-normal-form-explained-in-simple-english/
Hello guys, is there anyone who know how to run your django rest frame work api on the amazon servers?
Did anyone try using marshmallow flask and SQLalchemy together? I can't seem to get my query results to serialize 😩
from flask import Flask, request, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from sqlalchemy import or_
app = Flask(__name__)
DB_URL = 'postgresql+psycopg2://{user}:{pw}@{url}/{db}'.format(user='user',pw='pw',url='url',db='db')
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL
db = SQLAlchemy(app)
ma = Marshmallow(app)
class Model(db.Model):
__tablename__ = 'models'
username = db.Column(db.String(200), primary_key=True)
class ModelSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = Model
@app.route("/api/getModels", methods=['POST'])
def get_models():
filters = request.get_data()
f = json.loads(filters)
filters = f['filters']
query = db.session.query(Model).filter(or_(*[getattr(Model, selection ) >=25 for selection in filters])).all()
final_result = ModelSchema().dump(query)
# final_result returns {} :(
try using the "many" flag .dump(query, many=True)
Hey can someone help me with mySQL
SELECT DISTINCT e.fName, e.lName FROM Employee e, Dependant d WHERE e.salary > (select AVG(salary) FROM Employee) AND d.ESSN != e.SSN;
Im having an issue where the: *AND d.ESSN != e.SSN; * is not working and print everything and not excluding things.
I have a sqlite table with the following columns: id, timestamp, type, info (int, datetime, text, blob).
I want to do something like
select * from table
where timedifference < datetime.timedelta(minutes=30)
and timedifference = timestamp - datetime.datetime.utcnow()
I cant formulate how would I do this in my head. Help will be appreciated
Can someone explain to me why this wont work?
mycursor = db.cursor()
def pswdcheck():
mycursor.execute("SHOW TABLES")
for x in mycursor:
global dbpswd
dbpswd = x
upswd = input("What is the pasword?\n")
if dbpswd == "('" + upswd + "',)":
print("test")
main()
hi, i am working with mongodb cloud (pymongo driver) and i have there a collection of 1000 documents (200mb overall).
Each document is as follows:
{"_id": 1,
"a": oneLineDict, #Object
"b": { #Object
"1": ListOfHundredsSmallDicts1, #Array of Objects
"2": ListOfHundredsSmallDicts2,
...,
"up to 15": ListOfHundredsSmallDicts15},
"_id":2, #doc 2
}```
My code:
```py
BIG_LIST = mycol.find({"_id": {"$gte": 100, "$lte": 199}})
start_time = time.time()
for api in BIG_LIST:
print(int(time.time() - start_time))
break #just for this test
# only the first loop takes so long. The rest appear immediately.
# but every 100 it stop for few minutes.
> 65```
It takes over a minute to run this single line `for api in BIG_LIST`! Is there any way i can make it any faster?
I have tried to connect to mongodb cloud from my computer, and from heroku cloud (which was a little faster, but not significantly)
print(mycol.find({"_id": {"$gte": first, "$lte": last}}).explain())
> {'queryPlanner': {'plannerVersion': 1, 'namespace': 'mydatabase.mycollection', 'indexFilterSet': False, 'parsedQuery': {'$and': [{'_id': {'$lte': 100}}, {'_id': {'$gte': 199}}]}, 'winningPlan': {'stage': 'FETCH', 'inputStage': {'stage': 'IXSCAN', 'keyPattern': {'_id': 1}, 'indexName': '_id_', 'isMultiKey': False, 'multiKeyPaths': {'_id': []}, 'isUnique': True, 'isSparse': False, 'isPartial': False, 'indexVersion': 2, 'direction': 'forward', 'indexBounds': {'_id': ['[100, 199]']}}}, 'rejectedPlans': []}, 'executionStats': {'executionSuccess': True, 'nReturned': 100, 'executionTimeMillis': 0, 'totalKeysExamined': 100, 'totalDocsExamined': 100, 'executionStages': {'stage': 'FETCH', 'nReturned': 100, 'executionTimeMillisEstimate': 0, 'works': 101, 'advanced': 100, 'needTime': 0, 'needYield': 0, 'saveState': 0, 'restoreState': 0, 'isEOF': 1, 'docsExamined': 100, 'alreadyHasObj': 0, 'inputStage': {'stage': 'IXSCAN', 'nReturned': 100, 'executionTimeMillisEstimate': 0, 'works': 101, 'advanced': 100, 'needTime': 0, 'needYield': 0, 'saveState': 0, 'restoreState': 0, 'isEOF': 1, 'keyPattern': {'_id': 1}, 'indexName': '_id_', 'isMultiKey': False, 'multiKeyPaths': {'_id': []}, 'isUnique': True, 'isSparse': False, 'isPartial': False, 'indexVersion': 2, 'direction': 'forward', 'indexBounds': {'_id': ['[100, 199]']}, 'keysExamined': 100, 'seeks': 1, 'dupsTested': 0, 'dupsDropped': 0}}, 'allPlansExecution': []}, 'serverInfo': {'host': '*****', 'port': ****, 'version': '4.2.6', 'gitVersion': '***'}, 'ok': 1.0, '$clusterTime': {'clusterTime': Timestamp(1588233776, 1), 'signature': {'hash': b'*****', 'keyId': ***}}, 'operationTime': Timestamp(1588233776, 1)}
> (5 seconds)```
Is there a way to lock mysql database? From inserting data into it?
try using the "many" flag
.dump(query, many=True)
@runic pilot That was it! Thank you 🙂
Anyone know free mysql database hosts with remote connections????
i get this error
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'method' object is not subscriptable
from this code
results = collectionOwner.find["_id": 0]
pls help
im using mongoDB
nwm
find the problem
SELECT user_id, box_id, square_id, circle_id
FROM items WHERE '%_id' = '62184'```
how can I detect which of the items above has such a value?
what library are you using ? @lavish ferry
is there a way to ping a mongoDB?
Can someone recommend what to do when you have a database set up which includes shops, their products, sales, customers, and receipts? Since receipts have foreign key tie in to products, but shops can delete their products at any time, should we record all the product information in the receipts as well? Or should we soft delete products and maintain the foreign key link between receipts and products?
I worry about soft deleting because it's tough to maintain and do without breaking several things like on_delete primitives 🙂
But I also worry that it doesn't make sense to duplicate so much information across two tables
I'm fairly new at SQL and was wondering what are the pros/cons for creating and using a function as compared to using the WITH clause in T SQL?
using asyncpg, but this is in my sql query
@lavish ferry so any of the ids might have that value?
If that query doesn't work you can try
SELECT user_id, box_id, square_id, circle_id
FROM items WHERE '62184' IN (user_id, box_id, square_id, circle_id);
how do I get row count in python? I tried:
rowcount = mycursor.execute('SELECT * FROM bot_guilds')
But that prints "None"
I also tried:
rowcount = mycursor.execute('SELECT COUNT(*) FROM bot_guilds')
That also prints "None"
nice
has anyone here used psycopg2 to access postgres? i'm not able to connect and i'm not sure what exactly i'm doing incorrectly
FATAL: Peer authentication failed for user "postgres"
that's the exception
i'm using the default user postgres just to get connected then i'll try with a different user/role
postgres=# \conninfo
You are connected to database "postgres" as user "postgres" via socket in "/var/run/postgresql" at port "5432".
if anyone has any ideas please @ or dm me
How do I use SQLite3? I've never used SQL before and I just started needing it for a dpy bot
import sqlite3
conn = sqlite3.connect("file")
conn.execute("SQL STATEMENT")
@frank needle
Hmm
This is an example without value, but a quick pointer
Ok
If file does not exist, a new database is created, otherwise it is opened
Alright
Database normalization is the process of structuring a relational database in accordance with a series of so-called normal forms in order to reduce data redundancy and improve data integrity. It was first proposed by Edgar F. Codd as part of his relational model.
Normalization...
Some stuff to read
i am storing a list in database which contains (name, value, date,amount). i would like to make a map inside database using the date provided. and whenever i do select * from table, i should be able to categorize them according to its date. like (today's list) = maybe 5 records. yesterday's ...
@torn sphinx Are you storing the list in one field?
i wanna retrieve records, categorized according to their date
SELECT field1,field2,field3 FROM tablename WHERE date >= 2020-02-02
This would be general way to go about it
assuming the field type is DATE
no
no what?
i wanna do select * but later on categorize according date. like if belongs to today getting in one list. if belongs to other date should be stored on its relevant list
Then modify the query above using various date ranges
SQL only returns what you query
It does not have a concept of using different "lists" to return data
Or query a lot and sort using python
we can't use map in database ? to give each date a key then retrieve using that key ?
like all records which is saved today should be saved under key named "today"
And what if it is 0:00 on "today"? How are you going to update it?
But no, there is no such concept
just query using the actual date
that would be redundant data and violate the normal form
The date already reflects today
Some database systems may have a variable called TODAY to use in a query
The system you are proposing makes the database unreliable if a field is not updated, it violates the normal form and it would be clunky and inperformant to use.
If you want all data from today, SELECT field1, field2 from tablename WHERE date == "2020-05-02"
not only today. i want to list all records. but show in category, like today, yesterday, ...
As I said, sort it with Python. Have a look at datetime
Hi.
Could someone help me with my problem with SQLAlchemy.
I am trying to implement post-comments database and in comment table I have 2 primary key columns - comment_id and post_id (with relationship and foreign key to post table).
I want to know if there is way to make db set comment_id not always incresingly but starting from 1 when post_id changes.
For example:
When I have post_id 1 and add 3 comments (with ids 1, 2, 3 respectively), but when I add post with post_id 2 I want to get comment_id not 4 but 1.
Is there a way to do it?
I think was possible in postgres in some ways but I can not figure it out how to make the same for sqlalchemy
anyone help me with alembic migrations
it gives error in running alembic upgrade head
sqlalchemy.exc.nosuchmoduleerror can't load plugin sqlalchemy.dialects:driver
from configuration import app
from core.expense.models import user # added my model here
alembic_config = config.get_section(config.config_ini_section)
alembic_config['sqlalchemy.url'] = app.config['SQLALCHEMY_DATABASE_URI']
engine = engine_from_config(
alembic_config,
prefix='sqlalchemy.',
poolclass=pool.NullPool)
this is the code to be added to use --autogenerate and it says it will work...but i don't have a config file so i imported my app and models differently but i don't know where to import get_section from instead of config
CREATE TABLE ban list(
guild_id integer,
member_id integer,
ban_date datetime,
end_date datetime)
this is in sql lite why its not working
mycursor.execute(f"SELECT * FROM wp_users WHERE id = 1")
await ctx.send(mycursor.fetchall())
why does this not send anything?
just a guess: are you using an async sql client? If not, I don't know what happens
The ones that have used django for backend. What are your opinions?
I'm planning to go through backend with django
I'll like to know how it fits with React
Its kinda hard to know exactly where i should be asking this question, but does anyone have any tips on where to go looking for ontologies that have ID annotations? Also looking for an ontology that contains something you're looking for, but dont know what each ontology has is really annoying
I am just wondering, what should I use redis for?
And is it okay if I use Postgresql and Redis both?
Please ping me if you respond
http://prntscr.com/s9y8gw
I am having problems with cursor iteration (PyMongo & MongoDB) [https://discordapp.com/channels/267624335836053506/342318764227821568/705622919971340350]
So I thought maybe the problem is with my data, so I decided to do a test with the Sample Dataset of mongodb - http://prntscr.com/s9y9mh
I am running the following code for this test:
mycol = client["sample_airbnb"]["listingsAndReviews"]
a = mycol.find()
start_time = time()
for api in a:
pass
print(time() - start_time)
It print 212.84761023521423 ....
Isn't 3.5 minutes for such a task too much? Is there anything i can do about it?
how many documents are in that collection?
hardware and connection speed also affect that time
can't remember exactly how pymongo handles a cursor iterator
I thought it should be a matter of a few milliseconds
i mean usually it is but i don't know anything about your setup
if you're on dialup with a pentium 2, it'll take a while
"a while" is still less than 3.5 minutes i guess
that definitely shouldn't take that long but why it is i'm not sure honestly man
well, thanks, i am still searching google, no luck yet
Im looking for advice on repairing a CSV file that somehow ended up in disarray during a platform migration. I just created this post in r/learnpython but thought you guys might be able to help as well: https://www.reddit.com/r/learnpython/comments/gcn61k/looking_for_advice_on_automating_the_repair_of_a/ Any advice is appreciated.
hello @rigid terrace
I just look at your screenshot
I think this looks not so bad to fix
pseudo code:
Read in each row and split into an array
If rnc1 exists then process each column into a dict with key = rncn and val = value
if rnc1 does not exist then youre still processing previous rn-1c1 value so simply process each column into the dict again for rn-1cn .
you can easily check for exisitance of key/value to make sure you dont squash previous value (but from your data it looks like simply be duplcate)
if rnc1 already exits then you still need to process incase there are updates
if you can create a csv file using the data from your screenshot then I will write a quick script for you
but I am going into the woods for the afternoon and I return in 7 hours to check your reply
Hello, I'm trying to connect my genre and video together but i'm getting this error TypeError: Additional arguments should be named <dialectname>_<argument>, got 'backref'
I'm not very good at databases so I have no clue how to actually do it and just found it on some random stackoverflow question which I can't find anymore. Here's my models
Genre model
class Genre(db.Model):
__tablename__ = "genres"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
def __repr__(self):
return '<Genre %r>' % self.name
Video model
class Video(db.Model):
__tablename__ = 'videos'
# Values which are important
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), unique=False, nullable=False)
description = db.Column(db.String(250), unique=False, nullable=True)
views = db.Column(db.Integer, default=0, nullable=True)
genre = db.Column('Genre', backref='video_genre', lazy=True)
def __repr__(self):
return '<Video %r>' % self.title
nvm fixed it
Are there any websites or something that I can start to learn databases? I'm working on a discord.py bot and databases would be quite helpful
the postgresql documentation has a surprisingly good tutorial
how do I call/name these unnamed columns after rotation? df has no attributable columns when I print df.columns as well.
using pandas
Is there a way to have MySQL have default values for JSON?
Because it is annoying to have to define default json in my code to just insert it
@noble oak just search for 'learn sql' there are tons of resources online
I'm starting to think I've found a bug in django because this doesnt make sense. So, theres two models relevant to this, solve and challenge (removed almost everything thats irrelevant)
class Challenge(models.Model):
name = models.CharField(max_length=36, unique=True)
auto_unlock = models.BooleanField(default=False)
unlocks = models.ManyToManyField('self', related_name="unlocked_by", blank=True, symmetrical=False)
class Solve(models.Model):
team = models.ForeignKey(Team, related_name='solves', on_delete=CASCADE)
challenge = models.ForeignKey(Challenge, related_name='solves', on_delete=CASCADE)
There are 53 challenges in the database, but when I run this, it outputs 74:
solved_challenges = Solve.objects.filter(team=team).values_list('challenge')
print(len(Challenge.objects.annotate(
unlocked=Case(
When(unlocked_by__in=solved_challenges, then=Value(True)),
default=Value(False),
output_field=models.BooleanField()
)
)))```
And this only happens when a when statement is referencing solved_challenges
@woeful tusk I sent you a direct message!
ok I just finished
data = [
# Note: header row comented out.
# 'c1,c2,c3,c4,c5,c6,c7',
'c1r2,,c3r2,c4r2,c5r2,c6r2,c7r2',
',c2r2,,,c5r2,,',
',,,,,,',
',,,,,,',
'c1r3,,c3r3,c4r3,c5r3,c6r3,c7r3',
'c1r3,c2r3,,,c5r3,,',
'c1r3,,,,,,',
',,,,,,',
'c1r4,,c3r4,c4r4,c5r4,c6r4,c7r4',
'c1r4,c2r4,,,c5r4,,',
',,,,,,',
',,,,,,',
'c1r5,,c3r5,c4r5,c5r5,c6r5,c7r5',
'c1r5,c2r5,,,c5r5,,'
]
I made that data array for testing earlier. I just copied the data from the image you posted
Next the script processes each row and this is what the debug output looks like:
0 ['c1r2', '', 'c3r2', 'c4r2', 'c5r2', 'c6r2', 'c7r2']
0 ['c1r2', 'c2r2', '', '', 'c5r2', '', '']
0 ['c1r2', '', '', '', '', '', '']
0 ['c1r2', '', '', '', '', '', '']
1 ['c1r3', '', 'c3r3', 'c4r3', 'c5r3', 'c6r3', 'c7r3']
1 ['c1r3', 'c2r3', '', '', 'c5r3', '', '']
1 ['c1r3', '', '', '', '', '', '']
1 ['c1r3', '', '', '', '', '', '']
2 ['c1r4', '', 'c3r4', 'c4r4', 'c5r4', 'c6r4', 'c7r4']
2 ['c1r4', 'c2r4', '', '', 'c5r4', '', '']
2 ['c1r4', '', '', '', '', '', '']
2 ['c1r4', '', '', '', '', '', '']
3 ['c1r5', '', 'c3r5', 'c4r5', 'c5r5', 'c6r5', 'c7r5']
3 ['c1r5', 'c2r5', '', '', 'c5r5', '', '']
so that normalized each row with the first col
Then the sanitized output is:
0 ['c1r2', 'c2r2', 'c3r2', 'c4r2', 'c5r2', 'c6r2', 'c7r2']
1 ['c1r3', 'c2r3', 'c3r3', 'c4r3', 'c5r3', 'c6r3', 'c7r3']
2 ['c1r4', 'c2r4', 'c3r4', 'c4r4', 'c5r4', 'c6r4', 'c7r4']
3 ['c1r5', 'c2r5', 'c3r5', 'c4r5', 'c5r5', 'c6r5', 'c7r5']
So all the rows match up and the cols as well
however I did need to make some assumptions:
Data is treated as strings
The column header row is commented out
the verfy first data row has an entry in col1
Hello, quick question about sqlite3 database entries
does sqlite3 automatically add a column for entry #?
@grand trout look into subquery and other forms of join / subquery in Django because I suspect that what's happened here is you are doing one query and unioning both the solve and the challenge tables, so that's why you get an output higher than 53
#create table
cursor.execute("""CREATE TABLE all_table (
alert_type text,
zone int,
info float,
oid int
)""")
def submit():
# create database or connect to one
conn = sqlite3.connect('all_alerts.db')
# create a cursor
cursor = conn.cursor()
#insert into table
cursor.execute("INSERT INTO all_table VALUES (:alert_type, :zone, :info, :oid)",
{
'alert_type': type.get(),
'zone': zone.get(),
'info': info.get(),
'oid': delete_box.get()
}
)
# commit changes
conn.commit()
# close connection
conn.close()
#using tk, but this entry box is where I enter ID number
delete_box = tk.Entry(main, width=30)
delete_box.grid(row=5, column = 1)
delete_box_label = tk.Label(main, text = 'Select ID')
delete_box_label.grid(row=5, column=0)```
there are also entry boxes for alert_type, zone, and info. oid is supposed to be an ID number, that is associated with that database entry
I expect my database to have only 4 columns
but when I enter everything in, i get this...
[('high temp', 1, 15.0, 1, 1)]
What is that fifth value?
If i'm only using .get for 4 entry fields, why does my database end up having 5 columns? that fifth column increments up by one for every additional database entr
From where can I learn Django for free?
What's the most complete documentation / book
why programming is so hard
i hate it at the same time i love it
seeing results but the process is pain in ass
should i use pytables or is there something better y'all would recommend for writing a bot?
hi
what are the best db's to use?
what are the best db's to use?
@valid cobalt I think the starting point would be SQLite Browser easy and powerful and free 😄
Anyone here available to help me our real quick?
SQL = '''
INSERT INTO Customer(FirstName, LastName, City, Country, Phone)
VALUES (?,?,?,?,?)
;'''
def NewCustomer(FirstName, LastName, *args):
try:
cursor = conn.cursor()
cursor.execute(SQL,(FirstName, LastName, City, Country, Phone))
except Exception as err:
print('%sBe aware: %s' % (SQL, str(err)))
pass
finally:
print'Closing connection')
conn.commit()
return "The message you want to return"
how would i go about making the *args optional?
if i run this now, nothing will be appended to database if i'm missing City, Country or Phone
give them default values
eg None?
Hello is anyone familiar with Wordpress?
I’m trying to host only a database on their and connect it to my website that is on another server(Heroku)
Could Django be a alternative content management system
why do you need a cms? @zealous schooner
for blogs, static wins over wordpress
Static HTML has no attack angle, the hosting is dead cheap. I pay 3€/month and 7€/year for my domain
It’s for this company, they need a cms to update information. But the thing is they’ve used Wordpress previously before so... they’d rather that. The website is already coded up, with flask and a database. And they’re both hosted on heroku. Question is, is it possible to JUST integrate the database from heroku into the Wordpress and host it there for CMS
https://devcenter.heroku.com/articles/connecting-to-heroku-postgres-databases-from-outside-of-heroku
Heroku Postgres databases are designed to be used with a Heroku app. However, except for private and shield tier databases, they are accessible from anywhere and may be used from any application using standard Postgres clients. For private databases, outside access can be enabled using trusted IP ranges.
I mean I have all the SQL so I could dump it anywhere. My question is, could wordpresss only host databases?
Without a website included
And we could use that server to connect to my website(which is on another server)
That does not even make sense
I don’t know much about Wordpress
Oh okay
Why not run a REST API on Heroku?
Then you can pull whatever data you need via that
IIRC Wordpress can do some REST as well, but it's wordpress centric, so whatever your needs are it may or may not work
The WordPress REST API provides an interface for applications to interact with your WordPress site by sending and receiving data as JSON…
You think Django could be a good alternative?
for cms
They just need a user friendly reliable feature where they can update/delete from the database
I don't know enough about the project to give any recommendation, but for simple database updates there are middleware options that are far more secure than a public interface
BUt if it is a Flask App, why does it not have an admin panel?
You can even do my special brand of admin panel which involves vpn tunnels and using local addresses
so the admin panel does not face the public
I’m using MySQL as a dB, how do you get an admin panel?
I mean the app
CMS means Content Managment System, so why do you need an extra way to manage the content?
It’s not for me, it’s for the company. So after the website is in production, they would want to be able to modify information from the db but through Wordpress if possible
I’m not too familiar with Wordpress
I don't even know how to respond to that
Sorry 😂
So they had someone make an app with Flask but want to manage it with Wordpress
Yeah :/
Kind of
but you can’t bring that code to Wordpress right? lol if that even makes sense
manage db thru wordpress?
Yeah
i dont even understand that.
I think am done for today. I am going to bed.
just use something like squirrelSQL
or one of the many guis
maybe hire a real DBA for a day/week to sort it out for them
This is what happens when managers without IT knowledge make fancy presentations and use buzzwords they know jack about
and "cloud computing" "cloud storage"
well, that actually makes sense
cloud computing means being able to spawn a couple of VM when you need them
but serverless is just bullshit³, it still involves a server
I would argue that serverless implies lack of server management--you provide just the application, and someone else just runs it. But yeah, it's a big heavily buzzwordy. And lots of people don't seem to understand the restrictions.
AWS Lambda is a good example. You execute packaged functions in a small variety of languages, but other than them being on a server somewhere you don't have to think about the server at all. There is no storage, no persistence, and you simply pay for your total utilized resources rather than for "Space". Which for some things is great, but you'd need an external DB server or similar for proper storage.
💯
hey guys! Im trying to find a data for a project. Im interested in cryptocurrency. Want to find a legit source not keggle. Anybody give me some suggestion?
@safe pagoda i think there's a tutorial called 'django for girls' which is an ok intro
I have a desire to make a database for a project that stores user_settings, account info, etc.
Due to a certain nature of the project (for reasons) I would like to be able to use interpolation
e.g. f"{foo}:{bar}" for the database itself, allowing the users to make their own foo bar
in their own way. A customizable database.
This db would be accessible from users logging into a website, and this is where they would
enter their foo and bar.
There has been discussion with associates as to which seems to be most practical, and what might be considered bad practice. 3 ideas have been formed and are requesting qualified feedback.
Idea #1 - SQL
SQL is a well known standard and provides serialization.
But with interpolation you can have security risks.
citation: https://cmatskas.com/ef-core-string-interpolation-and-sql-injection/
Idea #2 - Python Dictionary
But I am honestly prefering to implement something similar to a python dictionary.
https://developer.rhino3d.com/guides/rhinopython/python-dictionary-database/
As far as I know, I would just need to ensure a serialization implementation with the py-dict,
and would be sacrificing speed compared to sql. I'm sure there are possible security vectors
associated with python dictionaries.
Idea #3 - Have python dictionary values converted into sql and use sql for db updates.
This would most likely only be used for sql that required interpolation
https://stackoverflow.com/questions/9336270/using-a-python-dict-for-a-sql-insert-statement
All feedback is appreciated
EF Core has always provided support for inline SQL queries. This means that you could pass a T-SQL query to be executed through the current DbContext. A typical example would look like this: var term = "some search term"); var blogs = db.Blogs.FromSql($"SELECT * FROM dbo.Blogs
how do you get the total number of dates
and then store them in a numbered list
if the mongodb doc is:```
'5/2/20': '600'
'5/3/20': '610'
'5/4/20': '620'
'5/5/20': '630'
i want to store it as:```python
dates = ['5/2/20', '5/3/20', '5/4/20', '5/5/20']
userCounts = ['600', '610', '620', '630']
@wind raft total number of dates? What do you mean?
basically just convert the mongodb doc into a list like that
is my goal
through pymongo
@torn sphinx
speaking of MongoDB, @storm wigeon MongoDB sounds like what you're looking for. it's records are serialized as BSON...
{
'id': 091282930, # static key:value
'user_settings': { # static key, dynamic values
'favorite_color': 'void',
'favorite_band': 'Smash Mouth'
},
'custom_entries': { # static key, dynamic values
}
}
Is it safe to put your credentials.json into your project directory when making an app for ios and android while using the google sheets and google drive api?
im planning to use a google sheet as sort of a database
its fine if people see the database i just dont want people to edit it or poke around in my google drive
basically the app is a map of community food banks in the area, and the spreadsheet has all the coordinates of the food banks
why does python motorDict = (collection.find({'serverid': guildId})) equal AsyncIOMotorCursor(<pymongo.cursor.Cursor object at 0x7f87fc2876a0>)
for PyMongo (motor engine)
thanks @remote harness, I'll check it out and give it a try. From what I've found on the internet seems like a practical solution to the problem.
@lime grove it is not safe to do this. Any API keys or other credentials ARE visible to users who download your app if you store them in code, especially for users on Android who have their phones rooted. But anyone in possession of your app binary can decompile it and poke through it
whats a good way to use and manage many URLs (strings, basically)? I have many static URLs (especially image URLs) that I use on my application often. I want to be able to use and manage them easily. I tried using json but It feels off and inefficient. any advices?
Database
Hi, im new to databases
is it possible to make a column that auto updates itself,
for example a total value
that takes 2 items from the row and adds them up
and is it possible to have a one value be a list?
sqlite?
with sqlite to store a list you'd need to have the column be a string
then use json to dump the list as a string and save that
ah i see
as sqlite doesnt have that capability to store lists by default
tho its not hard todo
what about the other thing
as for auto count
yeah
to have it do automatically im not sure with lite
but would be easier enough to just have a func do it
but wouldnt suprise me if there was the ability to sum values in sqlite
If you want to store lists, look at nosql dbs
e.g. mongo
The question is, if you really need the upside and can live with the downside
A NoSQL db makes sense for e.g. large scale network monitoring like Icinga or PTRG, where you get a lot of values in very quick succession via SNMP
noSQL tends to only be good for smaller datasets however
Not really
i mean pretty much, something like mongo is limited to 9MB per request
which on larger sets can mean more requests to get data
Which is why I said if you get lots of values in quick succession
SNMP are lots of small values
So..
yh
personally i use Postgres for my production based stuff or Datomic
ive used mongo before but was getting about 40ms response time from the api compared to pg's 5ms but probably could of optimised stuff a bit more to lower that number
is there any way i can access a google sheets without authentication
not without api creds no
what even is the syntax error here?
c.execute(f'INSERT INTO members (id, money, workc, jailtime, stealc, rpsc, bank, bankc, total, hbank, heistamount, items, inuse, storage, isworking, tokens) VALUES ({userid}, {person["money"]}, {person["workc"]}, {person["jailtime"]}, {person["stealc"]}, {person["rpsc"]}, {person["bank"]}, {person["bankc"]}, {person["total"]}, {person["hbank"]}, {person["heistamount"]}, {items}, {inuse}, {person["storage"]}, {person["isworking"]}, {person["tokens"]});')
ive been staring at it for 10 mins i actually cant find anything wrong
im trying to convert my json file into a db
dont use f strings with sql
thats the problem?
makes them very liable to inject attacks
im only running this program once
no but this is just a headsup warning xD
btw sqlite doesnt need ;
i tried without it it still didnt work
lemme see
File "C:\Users\Zack Ghanbari\Desktop\Local Hierarchy\dbconverter.py", line 24, in <module>
c.execute(f'INSERT INTO members (id, money, workc, jailtime, stealc, rpsc, bank, bankc, total, hbank, heistamount, items, inuse, storage, isworking, tokens) VALUES ({userid}, {person["money"]}, {person["workc"]}, {person["jailtime"]}, {person["stealc"]}, {person["rpsc"]}, {person["bank"]}, {person["bankc"]}, {person["total"]}, {person["hbank"]}, {person["heistamount"]}, {items}, {inuse}, {person["storage"]}, {person["isworking"]}, {person["tokens"]});')
sqlite3.OperationalError: near ",": syntax error
damn i love sql errors lol
my first sql program :(
ok
wHAoh
i got
spammed
with 60 different messages
its cuz its in a for loop
i'll just send one
oof
INSERT INTO members (id, money, workc, jailtime, stealc, rpsc, bank, bankc, total, hbank, heistamount, items, inuse, storage, isworking, tokens) VALUES (659923837051207682, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, , , 2, False, 0);
ah wait
the items and inuse things were supposed to be empty strings
those values that arnt anything are what r breaking it
strange then
0, , , 2,
----^ this bit
yeah i saw
userid = int(person["user"])
items = ""
inuse = ""
for item in person["items"]:
items = f'{items} {item}'
for item in person["inuse"]:
inusename = item["name"]
inusetimer = item["timer"]
inuse = f'{inuse} {inusename} {inusetimer}'```
this is how i defined it though..?
here is one dict from hierarchy as an example
you sure the for loops arnt just skipping over it tho
"user": "259427180201639946",
"money": 0,
"workc": 0,
"jailtime": 0,
"stealc": 0,
"rpsc": 0,
"bank": 62,
"bankc": 0,
"total": 62,
"hbank": 62,
"heistamount": 0,
"items": [],
"inuse": [],
"storage": 2,
"isworking": "False",
"tokens": 0
},```
are those loops actually looping>?
not with how youve done it
why we dont use f strings along with the issue of sql attacks
we use ? to represent a value
then in execute you can do c.execute('somequery ?, ?, ?', (v1, v2, v3,))
why doesnt this work..?
def read_value(table, where, what, value):
conn = sqlite3.connect('hierarchy.db')
c = conn.cursor()
reading = c.execute('SELECT ? FROM ? WHERE ? = ?', (value, table, where, what))
conn.close()
return reading```
theres a syntax error in the reading statement
it only works for vaues not table names etc...
if you dont need the tables to be dynamic it would be better hard coding it
@ripe helm It can be if the table name cannot be influenced from the outside
but f strings would work
if the table name can be input from outside, then don't do it
it would be unusual to sql injection yourself with table names 
im confused
basically you'll be fine
as long as
the table name and column names
are not from some other user input
@brazen charm Uhm, just end the statement and start your own
that is how injection works
okkk
; SELECT * from user_passwords; --
@rain wagon ik, it was a joke, tho i dont know any real practical applications where the user would input the table name
Ok, he is looking for a way to dynamically use the table name. That is fine in itself, however, if the table name depends on an input, it needs to be safeguarded
yeah
It does not matter at which point you inject, any injection is bad
ik
also
how do i like
get the value
running that gives me this:
<sqlite3.Cursor object at 0x03C12DE0>
do cursor.fetchone() or somthing like cursor.fetchall()
basically
when you do cursor.execute()
what ever the database returns
the cursor essentially contains that data
we do cursor.fetchone() for getting a single tuple (row) or cursor.fetchall() to get all the rows that match out WHERE value
there are other methods also
when you do cursor.fetchall() i would advise saving it to a variable as its a generator so once its iterated over once or referenced once you cant do it again iirc
in the query
e.g
SELECT * FROM mytable WHERE cats = 5
if we called fetchone()
after executing that query
it would return the first row where cats = 5
* means all in this case
so select the entire row
we could do
SELECT name FROM mytable WHERE cats = 5 and call fetchone(), this would return the value in column name in the row where cats = 5
dw
how do i make it not a tuple
nevermind i did this
c.execute(f'SELECT {value} FROM {table} WHERE {where} = {what}')
reading = c.fetchone()
conn.close()
for x in reading:
reading = int(x)```
idk if theres a more efficient way but it works
@ripe helm int(reading[0])
oh i guess that works too
thx
how would i update every row in a database?
i want to go through each row indivually and change it
im not rlly sure if there is a good way of doing it
you could iterate over every row in the table and update it as u go
but that would probably be very bad practice
update tablename set column=value;
oh thanks
👍
quick and dirty method would be SELECT * FROM table and then do fetchall()
and get the len() of it
yolo
Is there such thing as appending to an existing list in postgres using asyncpg?
Basically, what I want to do is add all existing users in a member list row, in which I can check if member in list (the row) exists
oh sorry yes to who ever helped me with my question
the fact / dim statement was regarding star schema stuff
does anyone have any experience with sqlalchemy??
if yes, I would like to know how to access an object outside a session instead of copying the object data into another datastructure
if that makes any sense
do you . mean database session or do you mean user session
@ripe helm You should always do a qualified select instead of just select *
because that minimizes the risk of having data in a user form that the user isn't mean to see
true
wdym
He means if you are displaying data in what ever method you want to give the bare minimum amount of data as possible to stop the potential for leaking other data
anyone have experience with mongo
I have a question about why data i'm entering is being modified
by mongo
is there any good online courses to learn mySQL or postgre
do you . mean database session or do you mean user session
@woeful tusk I mean database session, it's an orm
Hey if anyone has experience with SQLAlchemy trying to do a self referential join that only loads certain instances of the relationship on the 'child' node. However, when I add a contains eager load to the query it filters the relationship column down to one instance.
e.g.
class Manager(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey("user.id", ondelete="CASCADE"), index=True)
location = db.Column(db.String())
same_managers = db.relationship(
"Manager",
primaryjoin=db.and_(db.remote(user_id) == db.foreign(user_id), db.remote(id) != db.foreign(id)),
uselist=True,
)
manager_alias = db.aliased(Manager)
managers = (
db.session.query(Manager).outerjoin((manager_alias, Manager.same_managers))
.filter(manager_alias.location == 'CA')
.options(db.contains_eager(Manager.same_managers.of_type(manager_alias)))
).first()
managers.same_managers == [Manager2] // should be multiple managers.
managers = (
db.session.query(Manager).outerjoin((manager_alias, Manager.same_managers))
.filter(manager_alias.location == 'CA')
).first()
managers.same_managers == [Manager2, Manager3, Manager4]
What are the most important syntax differences between sqlite3 and aoisqlite?
this might be a rooky mistake, but I need help with these, "check to see if there already isnt a submission" functions
def ifexisting(emp):
c.execute("""SELECT first FROM employees""")
print(c.fetchall())
print(emp.first)
for i in c.fetchall():
if i == emp.first:
print("yes")
else:
print("no")
this is the code
for some reason it doesnt print either yes or no
this is what the two c.fetchall() and emp.first prints out
[('jason',)] jason
@lilac bolt the way a cursor works is that when you call .execute(), all the results are saved in the cursor. Then, when you call fetchone() or fetchall() it grabs all the results and empties the cursor. So your second fetchall() won't get anything because the first one has already consumed all the results. You should store the result in a variable before printing it and using it, so that you don't fall into that trap
postgresql need elephantsql?
I am new to db, I want to learn PostgreSQL
Where to start?
Where to start?
@heady elk Go to google and search for "PostgreSQL"
how can i get the guild id, im trying to set costoum prefixes but it isnt working
async def get_prefix(bot, message):
guild_id = str(message.guild.id)
user = await bot.pg_con.fetch("SELECT * FROM prefix WHERE guild_id = $1", guild_id)
if message.guild.id == user['guild_id']:
prefixes = [user['prefix']]
else:
prefixes = []
i tried this but it dosnt do anything, it sends an error if the guild id isnt the same, but prefixes wont work
also using PostgreSQL
I want to make this:
create variable called xp.
check if XP for member_id is already existent in my database
if it is, then on_message() > add +1
if not, then create, give value of 0 and add +1
how can I do that in python?
if(xp != smth(int)):
then...
else
xp++
user = await self.bot.pg_con.fetch("SELECT * FROM users WHERE user_id = $1", author_id)
if not user:
await self.bot.pg_con.execute("INSERT INTO users (user_id, lvl, xp) VALUES ($1, 0, 0)",
author_id)
else:
await self.bot.pg_con.execute("UPDATE users SET xp = $1 WHERE user_id = $2",
user["xp"] + 1,
author_id)
@lime echo i do this
but i have it cross server
youd probably want to instert the guild id too
your get_prefix should return the prefixes?
Hey guys, hope you are all doing well and safe. I got a major problem in a face-recognition algorithm in python. I use face_recognition.
Here is my problem: in the example sketch, we load the image and then encode them. The fact is that it’s a lost of time if you do that every time you start the algorithm. So I decide to send all the encoding in a .csv file and every time we start the program, we load the data that are in the .csv file. The main problem is that those data from the /csv don’t work due to many problem especially with array in numpy.
I don’t want to spam this channel with code but if will be awesome if someone can help me solve this problem. I can send the code by pm.
Thank a lot guys
@rich trout thank you so much!
for some reason it still runs into a problem however
this is the new code
def ifexisting(emp):
c.execute("""SELECT first FROM employees""")
results = c.fetchall()
for i in results:
print(i)
print(emp.first)
if i == emp.first:
print("yes")
else:
print("fail")
and this is the output
('jason',)
jason
fail
apparently "("jason",)" isn't equal to "jason"
Someone able to tell me how to join tables in SLQALCHEMY so everything yellow is in one table?
The standard syntax is py query = db.session.query(ModelClass.value1, ModelClass2.value2).join(ModelClass2, ModelClass.value == ModelClass2.value).all()
In the query part, you select the values you need, in the join function you join the values on the join clause
This is equivalent to sql SELECT value1, value2 FROM ModelClass JOIN ModelClass2 ON ModelClass.value == ModelClasss2.value
I'm making something like "logs" that I'm recording in a db.. is there a way to do so that I can delete the earliest entries and limit the amount of rows to lets say 100?
(postgres if that matters)
@willow shard
@reef hawk With a constraint you can limit the rows to 1000, google it, it is pretty straight forward. Your code will need to delete "old" rows manually
ah okay, so there isn't a method that does it automatically?
You may be able to do it with a trigger maybe, I'd need to research that though
but trigger is a good keyword for looking that up
👌 ty
Very helpful to see the SELECT statement. Looks about right, will try ✌️
@somber hatch oh I only saw your message right now, thanks man!
the self.bot.pg_con... thing seems a bit complicated, I will try to do it a bit easier and I already have my ifs and else set up, I just need to know how to get the largest number in my xp_count
Can someone help me? I am about to loose my nerves:
@client.event
async def on_message(message):
db = sqlite3.connect("xp_system.sqlite")
for member_id in db.execute("""SELECT member_id FROM xpsystemdb"""):
if member_id == 0:
xp_count_new=0
post_count_new=0
db.execute("""INSERT INTO xpsystemdb(guild_id, member_id, xp_count, post_count) VALUES(?,?,?,?)""", (message.guild.id,message.author.id,xp_count_new, post_count_new))
else:
xp_count_old = db.execute("""SELECT MAX(xp_count) AS xp_count FROM xpsystemdb""")
post_count_old = db.execute("""SELECT MAX(post_count) AS post_count FROM xpsystemdb""")
xp_count_new=xp_count_old+1
post_count_new=post_count_old+1
db.execute("""INSERT INTO xpsystemdb(guild_id, member_id, xp_count, post_count) VALUES(?,?,?,?)""", (message.guild.id,message.author.id, xp_count_new, post_count_new))
line 25 Unsupported operand type(s) for +: 'sqlite3.cursor' and 'int'
and after that you have to pull out the data from that item
ayup
it might just be indexing into it db.execute(...).fetch_one()[0] I think
@lime echo I suggest you take the body of that function, and play with it outside of your bot, since that's easier
Let's me try.
It requires me to create another table and such... 😫 I will just fix it real quick on the bot.
hey, i use mysql, how can I give my pc acces on my mysql server?
GRANT ALL ON xino.* TO root@ip5f5ae3c8.dynamic.kabel-deutschland.de IDENTIFIED BY "anotherPW"this doesnt work, error is ERROR 1064 (42000): 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 '-deutschland.de IDENTIFIED BY "anotherPW"' at line 1
it's a lot, I am overwhelmed now.
@client.event
async def on_message(message):
db = sqlite3.connect("xp_system.sqlite")
for member_id in db.execute("""SELECT member_id FROM xpsystemdb"""):
if member_id == 0:
xp_count_new=0
post_count_new=0
db.execute("""INSERT INTO xpsystemdb(guild_id, member_id, xp_count, post_count) VALUES(?,?,?,?)""", (message.guild.id,message.author.id,xp_count_new, post_count_new))
else:
xp_count_old = db.execute("""SELECT MAX(xp_count) AS xp_count FROM xpsystemdb""").fetchone()[0]
post_count_old = db.execute("""SELECT MAX(post_count) AS post_count FROM xpsystemdb""").fetchone()[0]
xp_count_new=xp_count_old+1
post_count_new=post_count_old+1
db.execute("""INSERT INTO xpsystemdb(guild_id, member_id, xp_count, post_count) VALUES(?,?,?,?)""", (message.guild.id,message.author.id, xp_count_new, post_count_new))
Cannot operate on a closed database.
It sounds like that I need a cursor.
@lime echo do you know how to get one..?
@ripe helm no.
its quite easy
here
you make it with c = conn.cursor()
or in ur case
db.cursor()
and then just change all ur executes things with c.execute()
if you are changing a value, at the end make sure u do db.commit()
and then finally put db.close()
Ignored Question.........................................
@ripe helm i will try that right now, thanks.
mhm
@ripe helm should I just use db.commit() once? or each time I change a value?
I already have it once at the end of my code.
Don't know if anyone has any rough estimates but how fast would it generally be to query a select for lets say a hundred million rows with 7 columns? I need to select all rows that have the same user_id for example
postgresql
ahh idk
@lime echo make sure you have db = sqlite3.connect("xp_system.sqlite"), then c = db.cursor()
I do have it.
do u have a rough estimate for sqlite3 then?
import discord
from discord.ext import commands
import datetime
import sys
import sqlite3
client = discord.Client()
@client.event
async def on_ready():
print("Bot is running")
@client.event
async def on_message(message):
db = sqlite3.connect("xp_system.sqlite")
c = db.cursor()
for member_id in c.execute("""SELECT member_id FROM xpsystemdb"""):
if member_id == 0:
xp_count_new=0
post_count_new=0
c.execute("""INSERT INTO xpsystemdb(guild_id, member_id, xp_count, post_count) VALUES(?,?,?,?)""", (message.guild.id,message.author.id,xp_count_new, post_count_new))
else:
xp_count_old = c.execute("""SELECT MAX(xp_count) AS xp_count FROM xpsystemdb""").fetchone()[0]
post_count_old = c.execute("""SELECT MAX(post_count) AS post_count FROM xpsystemdb""").fetchone()[0]
xp_count_new=xp_count_old+1
post_count_new=post_count_old+1
c.execute("""INSERT INTO xpsystemdb(guild_id, member_id, xp_count, post_count) VALUES(?,?,?,?)""", (message.guild.id,message.author.id, xp_count_new, post_count_new))
db.commit()
db.close()
client.run()```
@ripe helm
@reef hawk im not sure what you mean, but SELECT * FROM tablename WHERE userid = something, that will select all rows if the userid is something
oh yeah I meant the timing for it lol
oki
im not sure if this is the problem but
this is wrong:
for member_id in c.execute("""SELECT member_id FROM xpsystemdb""")
you gotta use .fetchall()
that'll return a tuple
@lime echo
c.execute("""SELECT member_id FROM xpsystemdb""").fetchall()?
@ripe helm
i normally do something like c.execute("""SELECT member_id FROM xpsystemdb""") something = c.fetchall()
Let's me try it
Hey, i am using pymongo and apparently whenever i try to make around 300+ update requests in less than a minute it lags the discord bot 🤔
would there be a fix for it
@ripe helm you can't imagine how I am happy right now.
It worked.
im happy to help 😄
hey guys I need help I need to create a form where people fill it out and when they press send it gets inserted into a database
i have the UI finished, and the flask server running, the flask server is connected to the oracle database
but I dont know how to actually send the information to the flask server
hey frenz. I'm trying to create some models but I'm having some issues conceptualizing. id appreciate some help from anyone willing. im using flask-sqlalchemy. The models are in the image.
Item is a collection of items, they can be harvestable, craftable, and they can appear in recipes.
Recipe is a collection of ingredients that are associated to an Item.
Ingredient is a the amount of a given item in a given recipe
I'm not sure if im saying that right. I'm failing with the relationship aspects
hey @tight hollow could you change your name to have ascii characters, so it is easily mentionable? (see our nickname policy in #rules)
hi i'm looking for some beginners info on how to start with databases. i'm a manufacturing engineer at work, and periodically, we need to create some scanning serial numbers and measurement process to sort/filter parts due to time of something else FUBAR. Anyway, long story short, i want to start learning how to get the code take inputs, stash it in a .db and at a separate packing station, give me a red/green flag as to its quality status in the .db
Hey if anyone is familiar with sqlalchemy or just databases in general. I have two tables and an association table that joins those two tables to create a many to many relationship. Every once in a while, only in my production setting, i'll get duplicate entries into that join table or if I put a unique constraint i'll get an error where an insertion is attempted that violates the unique constraint. I'm using the SQLAlchemy api to set these fields.
Fake examples below
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
class Pet(db.Model):
id = db.Column(db.Integer, primary_key=True)
users = db.relationship("User", secondary="pets_to_users")
pets_to_users = db.Table(
"users_pets",
db.metadata,
db.Column("user_id", db.Integer, db.ForeignKey("user.id")),
db.Column("pet_id", db.Integer, db.ForeignKey("pet.id")),
db.UniqueConstraint("user_id", "pet_id"),
)
# fake example of how it may be set
pet = Pets.query.first()
pet.users = User.query.all()
db.session.commit()
Any ideas, this one is causing quiet a bit of issues :/
Hey, actually this is more of a general question for database, I've heard somewhere that sqlite 3 is bad mainly because it does not support concurrency, is it true that it's bad because of that? If so, why or why not?
The context of my question is also mainly just on the application of discord bots, by the way. I'm asking because if there is a need to future proof by migrating database in the future if the bot gets bigger, I might as well get all the information I need first. Also because I'm rather comfortable with the library already so I don't really want to change if possible.
Im using Flask-SQLALCHEMY with MYSQL db. Problem is i loose connection very often. SO i must reload a page 4-5x until its ready and no error 500. This is the message:
sqlalchemy.exc.OperationalError: (MySQLdb._exceptions.OperationalError) (2013, 'Lost connection to MySQL server during query')
Or
(2006, 'MySQL server has gone away')
I have this in config:
app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {'pool_size' : 100, 'pool_recycle' : 280}
Any idea how to fix or whats the issue in general?
I just setup postgre and downloaded postgre extension on vsc, connect ECONNREFUSED 127.0.0.1:5432 error popup when at 6/7 connecting, what does it mean?
psql: error: could not connect to server: could not connect to server: Connection refused (0x0000274D/10061)``` SQL shell says this too
This channel have questions more than answers alot
Hi guys, hopefully there's someone awake here
Hello again, I have an issue writing my pandas dataframe to an sql table in a sqlite db, here's my code:
def sort_and_dump_data_to_db(data_frame): sorted_data_frame = data_frame sorted_data_frame.sort_values(by=['Popularity'], inplace=True, ascending=False) sorted_data_frame.to_sql(f'{artist_name}_Top_Songs',if_exists='replace',con=db_interface.create_connection()) return db_interface.cursor().execute(f'SELECT * FROM {artist_name}_Top_Songs')It loops forever at:
sorted_data_frame.to_sql(f'{artist_name}_Top_Songs',if_exists='replace',con=db_interface.create_connection())
@pliant spire
I posted this in the help channels but no luck, maybe I can get lucky here?
Just curious what people's thoughts are about testing on the same database you run in production? I use postgres in prod and test on sqlite. And after reading that it's a good idea to test your exotic, implementation-specific queries, I started thinking of using a postgres db in testing too. It wasn't easy to switch over though. Just keeping the DATABASE settings in my Django config the same for test and dev wasn't enough. I have a test suite in pytest and it just errors out when I try to use postgres... Anyone's thoughts?
can i install psotgresql + pgadmin so i can have an web ui thing on an ubantu 18.04 vps
@pliant spire I assume db_interface is an sqlalchemy Pool? Can you post the code initialising db_interface.
oh no, it's just a module that contains functions for interfacing with the db
This is the function I call:
def create_connection():
conn = sqlite3.connect(r'api_calls_and_sorted_data.db', isolation_level=None)
return conn
It actually ended up working, I just truncated the data_frame
turns out the to_sql of pandas is notoriously slow
def sort_and_dump_data_to_db(data_frame):
sorted_data_frame = data_frame
sorted_data_frame.sort_values(by=['Popularity'], inplace=True, ascending=False)
sorted_data_frame.drop_duplicates(subset='Name', inplace=True)
sorted_data_frame = sorted_data_frame[:50]
with db_interface.create_connection() as db_connection:
sorted_data_frame.to_sql(f'{artist_name}_Top_Songs',if_exists='replace',method='multi',con=db_connection)
return db_interface.cursor().execute(f'SELECT * FROM {artist_name}_Top_Songs')
This is what i'm trying to run now
apparently
method='multi'
in the to_sql function is supposed to make it faster
Should I learn first Databases, data-science or machine learning?
Now I have this error:
Traceback (most recent call last):
File "C:/Users/Administrator.DELL-26/projects/spotify_playlist_creator/sorter.py", line 39, in <module>
main()
File "C:/Users/Administrator.DELL-26/projects/spotify_playlist_creator/sorter.py", line 36, in main
sort_and_dump_data_to_db(data_frame)
File "C:/Users/Administrator.DELL-26/projects/spotify_playlist_creator/sorter.py", line 29, in sort_and_dump_data_to_db
sorted_data_frame.to_sql(f'{artist_name}_Top_Songs',if_exists='replace',method='multi',con=db_connection)
File "C:\Python37\lib\site-packages\pandas\core\generic.py", line 2663, in to_sql
method=method,
File "C:\Python37\lib\site-packages\pandas\io\sql.py", line 521, in to_sql
method=method,
File "C:\Python37\lib\site-packages\pandas\io\sql.py", line 1734, in to_sql
table.insert(chunksize, method)
File "C:\Python37\lib\site-packages\pandas\io\sql.py", line 755, in insert
exec_insert(conn, keys, chunk_iter)
File "C:\Python37\lib\site-packages\pandas\io\sql.py", line 679, in _execute_insert_multi
conn.execute(self.table.insert(data))
TypeError: insert() takes exactly 2 arguments (1 given)
@clever topaz
how can i look if an id is in a table
i want to take a guild id an look if the guild id is in there
@pliant spire I think the issue was that you were passing a function that creates the connection rather than the connection itself.
@clever topaz I'm not doing that anymore though
So your code is this?
def sort_and_dump_data_to_db(data_frame):
sorted_data_frame = data_frame
sorted_data_frame.sort_values(by=['Popularity'], inplace=True, ascending=False)
sorted_data_frame.drop_duplicates(subset='Name', inplace=True)
sorted_data_frame = sorted_data_frame[:50]
with db_interface.create_connection() as db_connection:
sorted_data_frame.to_sql(f'{artist_name}_Top_Songs',if_exists='replace',method='multi',con=db_connection)
You left the return statement out, but yes
So the return is to test that the data has been entered? It's incorrect - it should be db_connection.cursor not db_interface (which is the module name, I assume).
Try without multi first and see if that works.
Actually, i'm either an idiot or a genius
because that's just a function, this is what it calls:
def cursor():
conn = create_connection()
return conn.cursor()
Without multi it runs fine
Yeah, that's wrong.
I've a feeling that multi doesn't work with SQLite.
Actually, i'm either an idiot or a genius
because that's just a function, this is what it calls:
def cursor(): conn = create_connection() return conn.cursor()
@pliant spire This creates another connection - which is wrong.
It connects to the same db though
It's still two connections.
Independent of eachother.
'multi': Pass multiple values in a single INSERT clause. It uses a special SQL syntax not supported by all backends. This usually provides better performance for analytic databases like Presto and Redshift, but has worse performance for traditional SQL backend if the table contains many columns. For more information check the SQLAlchemy documention.
The first connection is closed though...
I don't think it's supported by the sqlite3 module but it may be by the sqlalchemy module:
The Insert construct also supports being passed a list of dictionaries or full-table-tuples, which on the server will render the less common SQL syntax of “multiple values” - this syntax is supported on backends such as SQLite, PostgreSQL, MySQL, but not necessarily others:
I did make the change to use the same connection though
The first connection is closed though...
@pliant spire Why not just use the same connection?
I dunno, so many ways to do things in python, never really sure how to choose which way to solve a problem
I'd use sqlalchemy as in the docs:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html
https://stackoverflow.com/a/14432914 - it also has the added feature of read_sql_table (see near the end of the answer)
Last thing - the less connections the better. If you can do it all with a single connection, then why create more?
Yeah, you're right, it's local though so...I dunno...maybe readability...i'm not even sure 🤦♂️
i have my database in my vps, i can connect to it with my browser, bu t can i connect to it with python?
What could be the potential reason for pymongo to be slow?
I am using postgres, and I have like 8 columns in my table. In my function, I need to check some data stored in one of the columns. Unfortunately it wont be possible in the where statement so I have to take all the data and then compare it.
My question is what will be more efficient:
select * from table
run my check on one of the attributes
use other attributes if check passes
2) ```
select check_coulum, primarykeycolumn from table
# run check on check_column
select * from table where (check returned true)
# do stuff
you could just use SQL to check before
can you provide more details? I'm super curious what check you want to do but can't due to a SQL restriction
SQL is actually able to do alot of stuff being a complete programming language
1 sec
https://www.w3schools.com/SQL/sql_check.asp tho this isnt the full docs this does have an example of using the CHECK
to answer your question, both are very bad, since you're doing a scan over the whole table. Because of this, your query performance between the two will be about the same (the worst it can be), and your next bottleneck will be transferring all that data over the network. Since option #2 limits the data transfer (by only using 2 columns instead of all 8 of them), that one will appear more performant. But that also assumes that the second query in #2 is almost unnoticable because it's so fast
SQL is NOT a programming language
SQL is a query language
What adds the logic to SQL is TRANSACT, please do not confuse the two
@brazen charm
it can be if you use the PL/pgsql extension https://en.wikipedia.org/wiki/PL/pgSQL
That is a dialect though
I don't mean to be a pain in the ass, but I think it is sometimes important to distinguish
I'm currently trying to make a simple wishlist using django and was currently trying to render something if the wishlist has no items, but it doesn't show up
<h1>Wish List Items</h1>
{% for item in item_list%} {% if item_list|length == 0 %}
<h3>No Wish Items Exist</h3>
<hr />
{%else %}
<h3>Hello</h3>
{% endif %} {% endfor %}
</body>```
is what I have for the html
This isn't related to databases
mb
@somber hatch please paste text and not images, also you'll need to show your model / schema and the query which throws this error
Hi guys I am creating a web app which would require me to continiously write updates to a Postgresql table...(Around 4000 updates every minute)...Anything I should watch out for or any best practice tips? I also plan to expose this table as a main part of my web app via a flask rest api
Hello everyone i'm trying to create a read only user for my tables. I see some documentation does gives access to tables and other to sequences. What does the sequence portion mean? See example below.
CREATE USER readonly WITH PASSWORD 'somepassword';
GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly;
// sequence on next step?
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO readonly
hey im using
a = pymongo delete_one
a.acknowledged shows true even if the document didn't exist. what's the way around that?
Hey, I created a user in mysql via CREATE USER 'narmy'@'%' IDENTIFIED BY 'Jo***'
Now I wanna connect to it in DBeaver, but there is a Error.
Who can help me?
I put in the IP of my Server, the user name narmy and my password
if i am creating a website that people across the USA, and potentially across the world would use, then i should use the timestamp with time zone data type, right? https://www.postgresql.org/docs/current/datatype-datetime.html
actually wait.. i think i just use timestamp without timezone and then use UTC in my app
hmmmmmm
and also USE_TZ = True
always use timestamps and always use UTC
ok so..
- in settings.py i should have
TIME_ZONE = 'UTC'andUSE_TZ = True - in my model, it should be
modifydate = models.DateTimeField()(the SQL will translate into"modifydate" timestamp with time zone NOT NULLper sqlmigrate
is this correct? thank you so much @celest blaze and @runic pilot
is this flask/sqlalchemy/postgresql?
No it's Django with the stock ORM and PostgreSQL
I didn't install sqlalchemy
It works fine without it
I can't really answer if the django models/settings look good, but the SQL looks good to me
ok cool ty
ok so I'm trying to parse through a json file that starts out something like [ { "id":8100, "key":"Domination", "icon":"perk-images/Styles/7200_Domination.png", "name":"Domination", "slots":[ { "runes":[ { "id":8112, "key":"Electrocute", "icon":"perk-images/Styles/Domination/Electrocute/Electrocute.png", "name":"Electrocute", "shortDesc":"Hitting a champion with 3 <b>separate</b> attacks or abilities in 3s deals bonus <lol-uikit-tooltipped-keyword key='LinkTooltip_Description_AdaptiveDmg'>adaptive damage</lol-uikit-tooltipped-keyword>.", "longDesc":"Hitting a champion with 3 <b>separate</b> attacks or abilities within 3s deals bonus <lol-uikit-tooltipped-keyword key='LinkTooltip_Description_AdaptiveDmg'><font color='#48C4B7'>adaptive damage</font></lol-uikit-tooltipped-keyword>.<br><br>Damage: 30 - 180 (+0.4 bonus AD, +0.25 AP) damage.<br><br>Cooldown: 25 - 20s<br><br><hr><i>'We called them the Thunderlords, for to speak of their lightning was to invite disaster.'</i>" },
when I do ```Python
with open('runeprocessing/runesReforged.json') as f:
data = json.load(f)
keystones = {}
normalrunes = {}
runes = {}
for runes in data:
print(runes["slots"])```
I get this back, but I'm unsure of how to parse any further into the file
I'd like to be able to parse slots-runes-id and get the id of some runes
@torn sphinx The answer here is ISO8601. UTC timestamps with timezone modifier
hello i have a question about Mongoengine
i am creating my schemas, and i was wondering if i can make a reference to a object in my fields ?
there is the ReferencField for referencing ot other Documents type object
but what if i want to store not Document type object but normal objects ?
should i store json, and made a json method for the given object or is there a cleaner method ?
What it's a good book to learn databases, ml and data-science?
Guys
@client.command()
async def update(ctx):
if isAdmin(ctx.author.id):
start_task = time.time()
cursor.execute("SELECT user, name FROM users")
for user, name in cursor:
current_name = client.get_user(int(user))
if current_name is None:
current_name = await client.fetch_user(int(user))
if name != current_name:
cursor.execute(f"UPDATE `gamers`.`users` SET `name`= '{current_name}' WHERE (`name` = '{name}');")
print(name)
database.commit()
end_task = time.time()
await ctx.send("Task completed in {} seconds.".format(end_task - start_task))
Basically this should update the names of the users in the database
but it stops the loop at the first row, idk why
You have any solution?
use two cursors?
or save your results into a variable with fetcahall() before looping
or just use fetchall in your for statement
the selection works
the problem comes here
but yeah, select is outside the for-loop
cursor.execute(SELECT) loads the results into the cursor
you then begin to loop over the cursor
while looping over the cursor (that still has results in it), you perform another execute call
does that add to the results? replace them?
the docs dont say
clearly its not behaving well
okay i did this
so in the string update we will have the final command that we have to execute
But is it possible to do cursor.execute with multiline strings?
executemany() if i remember off the top of my head allows you to execute multiple strings
or maybe argument multi=True?
@client.command()
async def update(ctx):
if isAdmin(ctx.author.id):
start_task = time.time()
cursor.execute("SELECT user, name FROM users")
update = ''
for user, name in cursor:
current_name = client.get_user(int(user))
if current_name is None:
current_name = await client.fetch_user(int(user))
if name != str(current_name):
update += f"UPDATE `gamers`.`users` SET `name`= '{current_name}' WHERE (`name` = '{name}');"
cursor.execute(update, multi=True)
database.commit()
end_task = time.time()
await ctx.send("Task completed in {} seconds.".format(end_task - start_task))
Everything ok but nothing changing in the database
Is there something wrong in my code?
@rain wagon ty
For some reason I can't import mysql.connector I have run pip install mysql-connector and pip install mysql-connector-python. It keeps giving me the error No module named 'mysql'
hello! I am currently trying to make a discord bot with some rpg functions. My bot has a few commands at the moment and the main currency can be given, earned, used, etc. However, I don't really know how I would make a decent inventory system. I am currently using sqlite.
@pulsar timber there are great tutroials out there that you could use, i literally learned databases in 5-10 minutes
it aint that hard
i suggest codeacademy
however after i learned how to use sqlite i realized how much better aiosqlite is for discord bots
since if sqlite runs into an error, it'll stop your entire bot
and im just too lazy to learn aiosqlite
o ok, will try codeacademy
I am trying to connect Python to a PSQL DB but get the error "OperationalError: FATAL: password authentication failed for user". I've gone into the command line and created a DB in psql as well as a user with password and given that user full privileges. I try logging in via Python but can't authenticate for some reason with the same supplied username
How can I install mysql connector on linux ubuntu?
message_member_id= c.execute("""SELECT xp_count from xpsystemdb WHERE member_id ='message.author.id'""")
What's wrong with this line of code?
beats me
does it emit an error when you run it?
Or does it just not do what you'd hoped?
I'm guessing the latter
I assume message.author.id is a python expression
I also assume something like this is what you want: message_member_id= c.execute("""SELECT xp_count from xpsystemdb WHERE member_id = ?""", message.author.id) (the ? might need to be a %s instead; I can never keep those two straight)
@lime echo 
- It runs.
- Indeed, it doesn't set any value to
message.author.id, which is something I don't hope for. - Let's me try it real quick.
- It's indeed a python expression.
@celest blaze
It didn't work.
How do I store big int in aeiosqlite3?
Member ID shows as 2.5345456e+17 rather than 345345345346456457
I found a solution, I should just use bigint instead of int as member_id column.
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
k
HEY
is there a way to run multiple lines at once for mysql in command line ?
for example i want to these commands at once run :
for example i want to these commands at once run :
source /expDATABSE2/classroomcollege_db_classroom_classes_classescoadec.sql;
source /expDATABSE2/classroomcollege_db_classroom_classes_classescoadec_groups.sql;
source /expDATABSE2/classroomcollege_db_classroom_classes_classescoadec_students.sql;
source /expDATABSE2/classroomcollege_db_classroom_classes_classescoadec_teacher.sql;
I have to release a bot that manages a SQL database
can someone help me to prevent sql injection?
I bad formatted all the queries, idk how to fix them
That is an sql injection angle right there
Did you even bother to google the basics?
cursor.execute("SELECT value1, value2 FROM users WHERE user_id LIKE ?", [user.id])
also never use *
- in this case will only select the row
it always selects the row
that is the point
If you have data in that row that is not meant to be seen, you can't leak it if you only select what you need
And what formatting should i use in order to avoid SQL I?
he just showed you
diffrent libs have diffrent place holders
but e.g sqlite uses ? as a place holder
like he showed above
How to check if a record is existent or not, and return a bool?
SELECT TOP 1 1 and IF EXIST (SELECT) won't do the job for me because I want a bool return, not a value return.
I could solve it by using if len(str(member_id_check)) == 0;
What's wrong with this?
member_id_check = c.execute("""SELECT MAX(xp_count) FROM xpsystemdb WHERE member_id=?""", message.author.id).fetchone()[0]```
Error: ValueError: Parameters are of unsupported type.
bigint @hazy mango
@lime echo And message.author.id?
It's bigint @clever topaz .
Can you print it?
Yes!
Can you print it?
@clever topaz By this I mean can you paste it here?
238435934708826112
Try with just the number 1 instead of the variable.
member_id_check = c.execute("""SELECT MAX(xp_count) FROM xpsystemdb WHERE member_id=?""", 1).fetchone()[0]
Actually try this:
member_id_check = c.execute("""SELECT MAX(xp_count) FROM xpsystemdb WHERE member_id=?""", (message.author.id,)).fetchone()[0]
That should work.
Let's me try it out
It doesn't work with 1
It worked, but then:
if len(str(member_id_check[0])) == 0:
int object is not subscriptable.
Let's me try to fix it real quick
Nice it seems that you have to pass a tuple
This:
member_id_check = c.execute("""SELECT MAX(xp_count) FROM xpsystemdb WHERE member_id=?""", (message.author.id,)).fetchone()[0]
Should be:
member_id_check = c.execute("""SELECT MAX(xp_count) FROM xpsystemdb WHERE member_id=?""", (message.author.id,)).fetchone()
Since fetchone only selects one item anyway (or None if it fails).
Also your if should be:
if member_id_check:
(Which checks if it is None or a returned row)
Interesting.
Well, I want to know if member_id_check is null or not.
Do you think that if member_id_check: will check if it's null or not?
@clever topaz
Yes.
if member_id_check is identical to if member_id_check != False and if member_id_check != None.
In this context, the latter.
Awesome.
xp_count_old = c.execute("""SELECT MAX(xp_count) FROM xpsystemdb WHERE member_id=?""", (message.author.id,)).fetchone()
print(xp_count_old)
xp_count=xp_count_old+1```
It prints: (14,) instead of 14
Error: Can only concentrate tuple (not "int") to tuple.
@lime echo Yes, because it returns a row which usually has more than one field. You do need the [0] to access that item.
But it should be accessed inside an if statement which checks that the row is not null.
So:
row = c.execute("""SELECT MAX(xp_count) FROM xpsystemdb WHERE member_id=?""", (message.author.id,)).fetchone()
if row:
xp_count_old = row[0]
print(xp_count_old)
xp_count=xp_count_old+1
I thought that fetchone() would solve it.
Oh nice, I have tried this but it didn't work:
xp_count=xp_count_old[0]+1
I thought that
fetchone()would solve it.
@lime echo
No, because with this:
c.execute("""SELECT MAX(xp_count) FROM xpsystemdb WHERE member_id=?""", (message.author.id,)).fetchone()[0]
If fetchone returns None then you get:
None[0]
Which will obviously give an error.
I get it.
Name row isn't defined.
For this code:
row = c.execute("""SELECT MAX(xp_count) FROM xpsystemdb WHERE member_id=?""", (message.author.id,)).fetchone()
if row:
xp_count_old = row[0]
print(xp_count_old)
xp_count=xp_count_old+1```
@clever topaz
Hello everybody
I know Pure sqlalchemy and flask_sqlalchemy which one is better to use with flask? Or no difference?
What do you call a database that is hosted in the directory? I dont wnat to have to set up a whole sql database, i just want the database to be stored in one file that it loads
thats not how it works
you have sqlite that only has a single sqlite file but its not good for scale
im just making a small discord bot so im not woring about something crazy
and also i dont really like using raw sql. Is there good wrapeprs around it?
i think this is what i am looking for
For this code:
row = c.execute("""SELECT MAX(xp_count) FROM xpsystemdb WHERE member_id=?""", (message.author.id,)).fetchone() if row: xp_count_old = row[0] print(xp_count_old) xp_count=xp_count_old+1```
@lime echo Did you fix it?
@clever topaz no, I haven't fixed it yet.
It says that row is undefined.
Can you paste the full error?
Sure.
if row:
NameError: name 'row' is not defined.```
Line 37-38:
if row:
xp_count_old=row[0]```
Did you put row = c.execute("""SELECT MAX(xp_count) FROM xpsystemdb WHERE member_id=?""", (message.author.id,)).fetchone() before that line?
@lime echo
Can you paste your lines 30-40
No!
I think you've got some flow control which is causing it to work differently to how you expect.
xp_count_old = c.execute("""SELECT MAX(xp_count) FROM xpsystemdb WHERE member_id=?""", (message.author.id,)).fetchone()
Oh right, that's why!
if message.content =="!xp":
await message.channel.send(f"Your experience is {xp_count_new}")
else:
xp_count_old = c.execute("""SELECT MAX(xp_count) FROM xpsystemdb WHERE member_id=?""", (message.author.id,)).fetchone()
if row:
xp_count_old=row[0]
print(xp_count_old)
xp_count=xp_count_old[0]+1
post_count_old= c.execute("""SELECT max(post_count) FROM xpsystemdb WHERE member_id=?""", (message.author.id,)).fetchone()```
@lime echo Try:
row = c.execute("""SELECT MAX(xp_count) FROM xpsystemdb WHERE member_id=?""", (message.author.id,)).fetchone()
if row:
xp_count_old=row[0]
print(xp_count_old)
xp_count=xp_count_old[0]+1
That should work. Note row is the name we store the fetchone in.
Use sqlalchemy if you can @torn sphinx
Takes care of sanitization automatically
And turns your db rows into python objects
Pain in the ass to set up
But super slick when you get it working
@clever topaz I tried that.
So, it works, the bot launches and all, but it doesn't store any data in my database anymore.
You don't seem to have any INSERTS @lime echo .
@clever topaz I do.
print(xp_count_old) prints None.
Where are your inserts?
Also try print(row) before print(xp_count_old)
@lime echo
Do you ever commit the cursor @lime echo ?
@clever topaz
Can you post your whole code?
I do.
Yes I can.
import discord
from discord.ext import commands
import datetime
import sys
import sqlite3
class XpSystemdbcog(commands.Cog):
def __int(self, bot):
self.bot=bot
@commands.Cog.listener()
async def on_message(self, message):
db = sqlite3.connect("xp_system.sqlite")
c = db.cursor()
member_id_check = c.execute("""SELECT MAX(xp_count) FROM xpsystemdb WHERE member_id=?""", (message.author.id,)).fetchone()
if len(str(member_id_check))==0:
xp_count_new=0
post_count_new=0
c.execute("""INSERT INTO xpsystemdb(guild_id, member_id, xp_count, post_count) VALUES(?,?,?,?)""", (message.guild.id,message.author.id,xp_count_new, post_count_new))
if message.content =="!xp":
await message.channel.send(f"Your experience is {xp_count_new}")
else:
row = c.execute("""SELECT MAX(xp_count) FROM xpsystemdb WHERE member_id=?""", (message.author.id,)).fetchone()
if row:
xp_count_old=row[0]
print(row[0])
print(xp_count_old)
xp_count=xp_count_old+1
post_count_old= c.execute("""SELECT max(post_count) FROM xpsystemdb WHERE member_id=?""", (message.author.id,)).fetchone()
author_id = message.author.id
print(author_id)
post_count=post_count_old[0]+1
print(post_count_old)
c.execute("""INSERT INTO xpsystemdb(guild_id, member_id, xp_count, post_count) VALUES(?,?,?,?)""", (message.guild.id,message.author.id, xp_count, post_count,))
db.commit()
if message.content =="!xp":
await message.channel.send(f"Your experience is {xp_count}")
db.close()
def setup(bot):
bot.add_cog(XpSystemdbcog(bot))
🤔 even print(row) returns None
@clever topaz
@lime echo
import discord
from discord.ext import commands
import datetime
import sys
import sqlite3
class XpSystemdbcog(commands.Cog):
def __int(self, bot):
self.bot=bot
@commands.Cog.listener()
async def on_message(self, message):
db = sqlite3.connect("xp_system.sqlite")
c = db.cursor()
member_id_check = c.execute("""SELECT MAX(xp_count) FROM xpsystemdb WHERE member_id=?""", (message.author.id,)).fetchone()
# Member doesn't exist - add
if not member_id_check:
xp_count_new=0
post_count_new=0
c.execute("""INSERT INTO xpsystemdb(guild_id, member_id, xp_count, post_count) VALUES(?,?,?,?)""", (message.guild.id,message.author.id,xp_count_new, post_count_new))
if message.content == "!xp":
await message.channel.send(f"Your experience is {xp_count_new}")
else:
row = c.execute("""SELECT MAX(xp_count) FROM xpsystemdb WHERE member_id=?""", (message.author.id,)).fetchone()
if row:
xp_count_old=row[0]
print(row[0])
print(xp_count_old)
xp_count=xp_count_old+1
post_count_old= c.execute("""SELECT max(post_count) FROM xpsystemdb WHERE member_id=?""", (message.author.id,)).fetchone()
author_id = message.author.id
print(author_id)
post_count=post_count_old[0]+1
print(post_count_old)
c.execute("""INSERT INTO xpsystemdb(guild_id, member_id, xp_count, post_count) VALUES(?,?,?,?)""", (message.guild.id,message.author.id, xp_count, post_count,))
db.commit()
if message.content =="!xp":
await message.channel.send(f"Your experience is {xp_count}")
db.close()
def setup(bot):
bot.add_cog(XpSystemdbcog(bot))
if len(str(member_id_check))==0: was wrong - so I changed it.
Did it work? @lime echo
I think that this is a tautology:
else:
row = c.execute("""SELECT MAX(xp_count) FROM xpsystemdb WHERE member_id=?""", (message.author.id,)).fetchone()
if row:
xp_count_old=row[0]
print(row[0])``` to
```else:```
Well it's better but it doesn't store data in my database.
@clever topaz
I also have an issue with this
xp_count=xp_count_old+1 since xp_count is None
@lime echo
import discord
from discord.ext import commands
import datetime
import sys
import sqlite3
class XpSystemdbcog(commands.Cog):
def __int(self, bot):
self.bot=bot
@commands.Cog.listener()
async def on_message(self, message):
db = sqlite3.connect("xp_system.sqlite")
c = db.cursor()
member_id_check = c.execute("""SELECT MAX(xp_count) FROM xpsystemdb WHERE member_id=?""", (message.author.id,)).fetchone()
# Member doesn't exist - add
if not member_id_check:
xp_count_new=0
post_count_new=0
c.execute("""INSERT INTO xpsystemdb(guild_id, member_id, xp_count, post_count) VALUES(?,?,?,?)""", (message.guild.id,message.author.id,xp_count_new, post_count_new))
db.commit()
if message.content == "!xp":
await message.channel.send(f"Your experience is {xp_count_new}")
else:
row = c.execute("""SELECT MAX(xp_count) FROM xpsystemdb WHERE member_id=?""", (message.author.id,)).fetchone()
xp_count_old=row[0]
print(row[0])
print(xp_count_old)
xp_count=xp_count_old+1
post_count_old= c.execute("""SELECT max(post_count) FROM xpsystemdb WHERE member_id=?""", (message.author.id,)).fetchone()
author_id = message.author.id
print(author_id)
post_count=post_count_old[0]+1
print(post_count_old)
c.execute("""INSERT INTO xpsystemdb(guild_id, member_id, xp_count, post_count) VALUES(?,?,?,?)""", (message.guild.id,message.author.id, xp_count, post_count,))
db.commit()
if message.content =="!xp":
await message.channel.send(f"Your experience is {xp_count}")
db.close()
def setup(bot):
bot.add_cog(XpSystemdbcog(bot))
Not exactly a tautology as row may be null (as in this case though it isn't being detected as such).
However I found the mistake.
You didn't have a commit for the first insert.
I still do have this problem with
print(row[0])
print(xp_count_old) being None
Hence
xp_count=xp_count_old+1 doesn't work.
No.
@lime echo Rather than INSERT INTO xpsystemdb(guild_id, member_id, xp_count, post_count) VALUES(?,?,?,?) try INSERT INTO xpsystemdb VALUES(?,?,?,?)
Oki
I still do have this problem with
print(row[0])
print(xp_count_old) beingNone
Hence
xp_count=xp_count_old+1doesn't work.
@lime echo This issue won't fix until data is being saved. Also can you printmember_id_check?
I will try.
Ah I see why.
Even when null, it returns (None,) which is not none, thus it always goes to the else.
@lime echo Try this:
import discord
from discord.ext import commands
import datetime
import sys
import sqlite3
class XpSystemdbcog(commands.Cog):
def __int(self, bot):
self.bot=bot
@commands.Cog.listener()
async def on_message(self, message):
db = sqlite3.connect("xp_system.sqlite")
c = db.cursor()
member_id_check = c.execute("""SELECT MAX(xp_count) FROM xpsystemdb WHERE member_id=?""", (message.author.id,))
# Member doesn't exist - add
if member_id_check.rowcount == -1:
xp_count_new=0
post_count_new=0
c.execute("""INSERT INTO xpsystemdb(guild_id, member_id, xp_count, post_count) VALUES(?,?,?,?)""", (message.guild.id,message.author.id,xp_count_new, post_count_new))
db.commit()
if message.content == "!xp":
await message.channel.send(f"Your experience is {xp_count_new}")
else:
row = member_id_check.fetchone()
xp_count_old=row[0]
print(row[0])
print(xp_count_old)
xp_count=xp_count_old+1
post_count_old= c.execute("""SELECT max(post_count) FROM xpsystemdb WHERE member_id=?""", (message.author.id,)).fetchone()
author_id = message.author.id
print(author_id)
post_count=post_count_old[0]+1
print(post_count_old)
c.execute("""INSERT INTO xpsystemdb(guild_id, member_id, xp_count, post_count) VALUES(?,?,?,?)""", (message.guild.id,message.author.id, xp_count, post_count,))
db.commit()
if message.content =="!xp":
await message.channel.send(f"Your experience is {xp_count}")
db.close()
def setup(bot):
bot.add_cog(XpSystemdbcog(bot))
The None is inside the tuple which is an object thus not None.
Oh I get it.
By the way, you're right because print(member_id_check) doesn't execute.
if member_id_check.rowcount == -1:
'tuple' object has no attribute 'rowcount'
member_id_check = c.execute("""SELECT MAX(xp_count) FROM xpsystemdb WHERE member_id=?""", (message.author.id,)) without the .fetchone()
Oh oki
Oh my God, I can't believe. It stores data in my database now!
It doesn't increment anything but at least, it store data.
Nice!
Thank you so much.
No worries.
@clever topaz can you still help me figure out a solution for another problem?
If yes, then here is the code
if member_id_check.rowcount == -1:```
oh my God I can see why it doesn't work
let's me try smth real quick 😛
@clever topaz the bot is fixed, and it works completely well ✅
thank you for your help!
hi
"SELECT id, elo FROM stats WHERE elo = 2000"```
how do i do a range from 2000-2200
i want everyone with between 2000 and 2200
probably something like WHERE 2000 <= elo <= 2200
depends on the database
not really a python question
idk if this is the wrong channel for this but how do I get rid of this popup when there is no installation visibly running? I tried twice to download and install MySQL but the first few times, it crashed or paused and wouldn't pick up again. I've since deleted the installers and tried again. I also checked the task manager to see if it was running there but nothing showed up besides the apps I intentionally had open.
save yourself the hassle and dont use mysql
if you're gonna go through the effort of setting up the server and all that you might aswell use postgres
PostgreSQL best sql
The Django ORM/Migration tool should create the tables for you. If you've defined your modules, then you need to use manage.py and migrations/makemigrations to let the tool create the tables for you
The django tutorial docs should explain that
But I defined modules, maked migrations
did you run python manage.py makemigrations followed by python manage.py migrate?
yes
My database normally works, but I want to have columns
like firstname - lastname - email
in mongoDB you must have the _id, how can i get the last id so the new id can be +1 to the last one
i jsut tried this xd
dont know why i thought that would work xd
@somber hatch Apparently $inc can be used - https://stackoverflow.com/a/17054663
yeah but how could i do it lol
Is there a way to add a function to a sqlalchemy query, in place?
db.session.query(AssessmentPlan, func.timezone("US/Pacific", AssessmentPlan.updated_at))
In this example, I get two different results (<AssessmentPlan 1>, datetime.datetime(2020, 5, 11, 12, 0, 59, 913401)), but I really just want the (<AssessmentPlan 1>), with the updated_at column adjusted in place
hey guys what dbms would you recommend for a beginner like me. I've heard of SQLite but I think it's not as secure and doesn't have that many datatypes as mysql, I've also heard of mongodb. Those are pretty much the only three I know, pls can anyone give me some direction
SQlite >>>>>> MongoDB
You're in a Python channel, so the obv candidate is Postgres. But SQLite is no slouch. It depends on what you are doing.
Why unfortunately
Their complexity are not the same
and as far as how easy one is, NoSQL is close to the json format
Does anyone knows how i can create multiple databases, iam doing it in flask with sqlalchemy, one should contain users, 2nd posts and 3rd comments
So is mongo that bad?
oh so mongo is not an rdbms
it's not relational, no
nice, they're usually useful for things like that
why is this:
conn = sqlite3.connect('hierarchy.db')
c = conn.cursor()
c.execute('SELECT * FROM polls')```
giving me:
```sqlite3.OperationalError: no such table: polls```
It was working fine before, but i changed up a couple lines and now it doesnt work..??
maybe there is no table such table as "polls" @ripe helm
maybe your python script doesn't run in the destination working dir and sqlite3 creating a new "hierarchy.db" file
im 100% sure it exists
ive been using it
i just changed a couple lines that has nothing related with it
and now it doesnt work
in fact, none of my databases work
strange.. i did literally nothing and it works now
Small sqlalchemy session question I’m not finding the answer too online.
Are sqlalchemy session automatically closed when they’re part of a function that has returned?
@uncut egret quit the database and launch it again.
And the bot, if you're using a Discord bot.
I have quite a dumb (tired) question I have the following schema: https://mystb.in/qimuzodiju.sql
Basically every continent has multiple chapters and every chapter has multiple stages. Would it be fine to have a relationship and a column with the continent id on Game.ContinentChapterStage?
@toxic rune It is fine to have FK to both the tables if that'd result in any performance improvement. But this is usually considered a bad design, given that you can get the Continent from ContinentChapter
Ah I see that makes sense thanks
did the sqlite can be run as cluster scheme?
@chilly creek Where do you get the data from?
@pale crest REST GET an api
And it sends you a 15GB response?
So it's paged?
yep
Ok, and what are you gonna do with it?
indexing till 5 million
The data, I mean
one key of the json is a string of tags, seperated by a space
I want to be able to get all indexes with a specific tag
some tags have up to 500k entries
What do you mean by "indexes"?