#databases
1 messages Β· Page 190 of 1
Maybe that lib is somewhat outdated?
maybe
Looks like the case since it was updated ~5 years ago
ah
I'd look for another firebase wrapper
I mean, you should do that π
!pypi firebase-admin i've used this in the past
although i think that will run all operations as an admin which may not be what you want
You have to install postgres DB API driver and change your connection string
psycopg2 for sync and asyncpg for async
Traceback (most recent call last):
File "test.py", line 1, in <module>
import pymango, secrets
File "/home/anandh/Documents/Projects/Python/arc-discord-bot/venv/lib64/python3.8/site-packages/pymango/__init__.py", line 4, in <module>
from resources import Charge as Charges
ModuleNotFoundError: No module named 'resources'```
got this error while on linux (opensuse tumbleweed)
code
import pymango, secrets
client = pymango.MongoClient(secrets.CONNECTION_STRING)
servers = client["servers"]```
You should add your username, password and db to that connection string
postgresql+psycopg2://username:password@host/database
Don't think so, what's SQLAlchemy here?
You have to change SQLALCHEMY_DATABASE_URI
Change it to new uri
^
Yeah, but you have to add your username, password and database
assuming you are trying to connect to a mongodb database, the library is called pymongo, not pymango
!pypi pymongo
Python driver for MongoDB http://www.mongodb.org
thanks
Hm, what do you mean by "mixed up"?
3, 5.. are ids, right?
How did you get that data?
You didn't order them
By default postgres returns rows in whatever order they're on disk
If you want to order them by id then add order_by
Also i would personally recommend to use sqlalchemy directly in your code
You're using flask_sqlalchemy
Modern sqlalchemy has different api:
slides = session.scalars(select(Slide).filter(Slide.keynote == keynote))
No, i don't think so, it looks like flask_sqlalchemy has a bit different api, also it's using now deprecated Query object
At least Select is preferred in 2.x version, which is now in development but preview is available in 1.4
You're most likely using 1.4, you can check that in your dependencies
order_by(Slide.id)
Share code?
Are you sure? This should order slides correctly
Share your slide model
Thanks!
What is the meaning of "NOT NULL" and "DEFAULT NULL" ?
class Keynote(db.Model):
id = db.Column(db.Integer, primary_key=True)
# user_id instead of user
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
@clever gate
why is your password column of such a long string?
that usually is a sign of people storing clear text passwords in the database, which isn't good security practices for you users
How do I set a max value for Integer column in sqlalchemy?
You can add CheckConstraint
oh, can you link the docs for it
https://docs.sqlalchemy.org/en/14/core/constraints.html
class Model(Base):
__tablename__ = "model"
__table_args__ = (CheckConstraint("amount >= 0"),)
amount = Column(Integer, nullable=False, default=0)
thanks
whats a very easy to use kv store that has a python client and an easy to use docker image?
redis would be perfect but my data is too large to store in memory
(i know that redis can persist to disk but from what i know it still needs to have the entire data in memory)
python client isnt even a must
Can someone DM me to jump in a quick voice chat, just need some help understanding some documentation
sorry, not really a recommendation as such, but here is a list if you haven't seen it already: https://db-engines.com/en/ranking/key-value+store
a vertical tiktok in the wrong orientation is probably not a good way to describe your problem for us
hello so guys
Can someone DM me to jump in a quick voice chat, just need some help understanding some documentation
Not null is setting constraint on a column not to accept null value and default null would be setting default value null if we dont give any value to that column while inserting data
Thanks
Hmm
Hi, one question, I'm using sqlite3 and when I want to insert something into my db it gives me this error back:
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 18 supplied.
Does anyone know why? I'm trying to save one string of numbers into there
regarding sqlite3, is there any way to monitor or βrefreshβ table data (not an update query, data is added to the table externally) as opposed to creating a for loop, making a new connection/cursor to requery everytime? Seems like when you make the connection it takes the current data/state of the table and isnβt a dynamic connection
it depends.
It can be done as a job to check any recent updates, as part of the app logic to send updates to a message or event broker, or by using CDC tools like https://debezium.io/.
Personally, I am not too fond of tools like debezium since they work at a much lower level than the app level and potentially create tight coupling.
Note: my bad, I missed the sqlite3 part. No idea about it, but the same ideas remain π
gdi1['Mean_Yrs_Schooling_Male']= gdi1['Mean_Yrs_Schooling_Male'].astype(float)
could not convert string to float: '..' any ideas ?
Anyone know why this is created a corrupted table/db file? No error messages are popping up.
import discord
from discord.ext import commands
import os
import asyncio
import aiosqlite
intents = discord.Intents()
bot = commands.Bot(command_prefix = "?", case_insensitive = True, intents = intents.all())
bot.remove_command('help')
@bot.event
async def on_ready():
print('Logged in as {0.user}'.format(bot))
async def load_extentions():
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
await bot.load_extension(f'cogs.{filename[:-3]}')
async def main ():
async with aiosqlite.connect('memes.db') as db:
async with bot:
bot.db = db
cur = await bot.db.cursor()
await cur.execute('''
CREATE TABLE IF NOT EXISTS memes (
messageid text PRIMARY KEY,
userid text NOT NULL,
username text NOT NULL,
timestamp text NOT NULL
)
''')
await bot.db.commit()
await load_extentions()
await bot.start(os.environ['botsecret'])
asyncio.run(main())
Anyone know if it's possible to write to a SQL server via Pandas to_sql() function while defining primary keys/indexes? Or do you have to go down to the SQLAlchemy level to define that?
I think to_sql method serves to insert data into db, not to define your tables
It both does and it doesn't. If the table doesn't exist, it will generate it using the dtypes assigned to your columns. But there doesn't seem to be a way to specify a SQL-level index or keys. I know Pandas uses SQLAlchemy under the hood, just looks like it doesn't expose that additional functionality from SQLAlchemy π¦
Hey @copper quest!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Hello guys i have a question for a personnal project (very dirty right now). I 'am trying to insert a whole data frame into an accdb database. The goal is to take an excel file full of data and insert it directly inside a table of the db. The goal would be to be able each month to run the code and have the new simulation data added to the current table. Right now i'am trying to insert the first excel file but iam running into some errors hat i'am not able to fix at the moment could you please help me or advice me on what is going on ?The error is : line 48, in <module>
cursor.executemany( '''INSERT INTO Seriatimo (
pyodbc.DataError: ('22003', '[22003] [Microsoft][ODBC Microsoft Access Driver]Numeric value out of range (34) (SQLExecDirectW)') . I do somethimes run into some syntax issues also. Thanks a lot for your help reallly appreciated https://paste.pythondiscord.com/zukohesana
Use https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.describe.html and see if any of the min / max are out of range in any of your columns based on the numeric types configured per column.
Any idea why this works correctly? I need to find all rows where at least one column is 'waldo', without using OR and IN.
CREATE TABLE foo (a1 text, a2 text, a3 text);
...
SELECT * FROM foo
WHERE NOT (a1 <> 'waldo' AND a2 <> 'waldo' AND a3 <> 'waldo');
https://www.db-fiddle.com/f/oL4TCq4vJBkorJuw9AKQdq/0
Specifically, shouldn't (a1 <> 'waldo' AND a2 <> 'waldo' AND a3 <> 'waldo') equal NULL if the first one or two columns are NULL?
Ohh wait I think I get it. If any of the conditions is False, then the parenthesized condition is false because NULL and FALSE is FALSE. And Trues don't add anything
well as always, typing the question out answers it
it's first selecting the rows where none of the columns are equal to waldo (a1 "is different from" waldo AND a2 "is different from" waldo and so on), and then negating it with the NOT to select the inverse
NULL doesn't really have anything to do with this other then that NULL is different from waldo just like anything other then waldo also is different from waldo
hi I am working on a project that downloads a CSV from a website and imports to database [my sql] please help me
ask your specific question here in the channel to see if anyone can help you with the problem you are having
Lol
hello! do you know how to do something like this
self.bot.pg_con.execute("DELETE FROM kennel WHERE pet = $1 AND userid = $2", pet, ix)
with postgres?
i just wanted to use a parameter instead a concrete value
like instead "where id=10" comparing it with a variable like " where id = client_id"
this looks syntactically fine. is there some error?
@burnt turret
what library are you using?
ah, i think psycopg has a different notation for parameter substitution. let me check
this is what asyncpg uses though
thank you. @burnt turret I tried different ways to struture the query but still not working.
wouldn't be better if i just import the other library?
remove the parentheses around the %s, and the second argument has to be an iterable
so cursor.execute("DELETE FROM ...", [id_cursor])
refer the examples in the page i linked above
omg, it worked
thank you so much @burnt turret
i struggled so hard with just a simple query
not a friendly syntax, but guess it's all lack of experience. 1st time managing dbs.
you'll get it π
Is there any way to write a BLOB or raw string to a file using psql (PostgreSQL client)?
how i can add many values in the (members ids)?
Use an association table:
CREATE TABLE member_roles(
user_id INTEGER NOT NULL,
role_id INTEGER NOT NULL,
PRIMARY KEY (user_id, role_id),
FOREIGN KEY (user_id) REFERENCES members(user_id),
FOREIGN KEY (role_id) REFERENCES role_data(role_id)
);
thanks
member_roles is a column for members?
no, no "roles" column in "members" and no "member ids" column in "role data"
you just join when you want the related data
Not sure if this is the right place to ask but best I got. Using MySQL, is there a good way to ensure concurrent INSERTs with AUTO_INCREMENT will work on a specific table and that they're as performant as possible? This specific table doesn't rely on the AUTO_INCREMENT values being consecutive but others in the DB do.
quick question, if I have the following columns: Name, Amt in Table1 and Query, FiltAmt in Table2 and I want to sum(Amt) in table1 / sum(FiltAmt) in table2. What would the optimal sql query be like?
I tried some thing like Select sum(Amt)/(select sum(FiltAmt) from table2) from table1; which works but not sure if this optimal
i think in general mysql itself can guarantee the safety of auto increment within a table (you should confirm this in the docs), but the problem is that you can't guarantee the order in which they are executed unless you explicitly serialize your requests somehow
that said, i don't think it's a good idea to ever rely on the insertion order with auto increment
optimal in what sense? database query planners are usually pretty smart. if you are doing performance tuning, learn to understand the EXPLAIN output for your specific databse
optimal in query execution time. is there any other way to write the above query with faster execution
let's say I am working with 200GB of data
personally i'd write the two select statements separately and compute the ratio in python after
makes sense
Alright, I'm trying to modernize a, uh, like six year old codebase and the community around it has relied on values being incremented consecutively, I don't want to have weird edge cases breaking that but part of my modernization is one table to track changes that I want concurrent inserts to, since it's polled then deleted every minute I'm using auto increments to for an ordering but I'm considering something like a NOW() timestamp instead, all I need to be able to do is easily identify which have been fetched with a WHERE clause rather than specify like a hundred thousand specific rows to delete.
in general i dont think theres a better way to compute this other than two SELECTs. i wouldn't worry about it. but always use EXPLAIN when in doubt, for performance
the auto increments should always be sequential from the perspective of actual writes to the database. but if they need to be ordered with respect to some sequence of events within your application, then i don't think you have any alternative but to forcibly serialize requests according to that sequence
actually im not even 100% confident that auto increment is fully thread safe
you'll have to check the mysql docs carefully
I read through the page on InnoDB auto increment locking, depending on the mode you set there's various reasons for it to have a increment lock on the table
There's one mode that doesn't guarantee values will be consecutive and one that does
One I forget
what if instead of concurrently writing to the database, you pull requests into batches and then do a single write every minute, or something like that?
I can't really, I'm basically logging changes to specific tables in triggers so they can be tracked and forwarded as subscriptions to users
Since the codebase is a six year old mess I can't just slap batching and stuff everywhere so the simplest solution is tracking before and after values through triggers then computing stuff later on the API side
If you need sequential integers and you don't want to switch to something like uuids you can use snowflake ids that discord uses π€
Maybe, but that'd be hard to do in a trigger
I might just use milliseconds since epoch
Yep, in a trigger that would be hard to do
I don't need guaranteed unique values, just need to know if something came before or after a given value
Multiple writes can occure in single millisecond though
Yeah, that's fine
Why not use a timestamp then?
Milliseconds or timestamp, I'm not sure which I'd end up choosing
Timestamp should be fine, it stores milliseconds too
As long as there's not 2+ writes to the same row in one millisecond (which, uh, given networking and stuff I strongly doubt will happen), then I don't really care
It would definitely happen depending on your orm
And even if their is, clients will get further updates on that model later and I'm going to recommend that once every day or so they update their cache to ensure nothing got missed somewhere
My guess is with the way things work there's like a one in ten trillion chance that a two queries on the same model run in the same millisecond
Depends on traffic, but yes
Postgresql for example has a select for update construct that would allow you to lock specific rows until you commit
π€
Made a type-checked async ORM wrapped around asyncpg. The part I like most about this is that the types of model fields always match, so you can have an ORM and not loose mypy/pyright support.
Examples under /examples and in the wiki, and I appreciate any feedback!
Project Repo: https://github.com/trigondev/apgorm
I also have a project that actually uses apgorm, https://github.com/TrigonDev/Starboard/tree/main/starboard/database
class User(apgorm.Model):
name = types.VarChar(32).field()
nick = types.VarChar(32).nullablefield()
primary_key = (name,)
user = await User.fetch(name="CircuitSacul")
reveal_type(user.name) # str
reveal_type(user.nick) # str | None
pretty neat
instantiating User does not seem to have type-checking though (its __init__ is just (**vals: Any) so i can do User(name=1)), is that intentional?
raise ConfigurationError(
pymongo.errors.ConfigurationError: The "dnspython" module must be installed to use mongodb+srv:// URIs. To fix this error install pymongo with the srv extra:
how to install this ?
how to make good data base
pip install dnspython π€
Are the queries typed as well?
https://paste.pythondiscord.com/wajuvejuxa Someone help with this code please
I wanna make a backend database for a job search engine. What would be better for it rdms or nosql
Cant we have column of list in aiosqlite?
Not "intentional", but it would be very difficult to get the columns into the init method in a way that typecheckers support
yes
somewhat
it's not perfect
the part that's really typehinted is the types of the model fields
Iirc mypy and other type checkers in general have support for dataclass-like types, but for more control you'd have to write custom plugin π€
you could probably mess around with dataclass_transform to at least make it work with pyright
^
Why do you need a list?
I'd say it depends, i don't really see a problem with sql there, but i didn't work with nosql
to save multiple channels ids in database
per guild
I have to write a report on comparing the 2. 1000-1500 words. But I have no idea what to write. Other than the standard differences between SQL and no SQL.
@paper flower @burnt turret yeah I might try dataclass transform. I don't want to use a plugin because then you (1) need the plugin installed and (2) only support mypy (not pyright, for example)
sqlite doesn't support arrays, you can use relationships for that
example?
class Guild:
id: int
class Channel:
id: int
guild_id: int # < Points to guilds.id
hey guys, if there's no unique value in a table, then is there no primary key then?
ie. area_id can be used a couple of times so that means that it's not a unique key right?
True.. any column which is primary key has to fulfill below criteria all vales have to be unique and no null value should be there
Does anyone know why my SQLite database loses its data after 12 hours?
or 24
it keeps losing data
That isn't really a known issue, can you give some more context? For example, are you running this on heroku or something like that?
On heroku, yes.
That's heroku's fault then, not sqlite https://help.heroku.com/K1PPS2WM/why-are-my-file-uploads-missing-deleted-from-the-application
You can try using something like their postgres add-on
Do you recommend any budget hosts instead which doesnt lose my data?
It'd depend on what you're doing, but the big providers like GCP/Azure etc will all have some free tiers and all
Discord bot hosting
I'm pretty sure there's a message pinned in #discord-bots with a list of cloud providers
Do u know how to use this?
i'm sure they have some tutorials on it
there's even a thread for that now, #965291480992321536
So i'm wanting to put info into an embed, but i want to get the information from the databse about that specifc trade, i tried this but it didnt work:
py trade = mycursor.fetch(f"SELECT trade FROM t_info WHERE channelID = {message.channel.id}")
trade = mycursor.fetch(f"SELECT trade FROM t_info WHERE channelID = '{message.channell.id}'")
add single quotes
ok
AttributeError: 'CMySQLCursor' object has no attribute 'fetch' this is his error
Oh, apologies. The fact that it is evaluating 'fetch' as an attribute rather than as a method leads me to believe that you might be using the wrong object type to access the database. Check to make sure whether there really is a 'fetch' attribute first.
CMySQLCursor.__dir__() or dir(CMySQLCursor) to get a list of all available methods for the object. Verify that fetch is one of them.
That looks a lot more complicated then i really want it to be...
I'm going to probably look for a host that supports SQL as my whole discord bot is using that already
You sure? Because this code is pretty up to date.
you mean sqlite3 more specifically?
yes
CMySQLCursor.__dir__(), where do i paste this?
!e print("hello".hellobello())
@next sparrow :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | AttributeError: 'str' object has no attribute 'hellobello'
!e print('hello'.dir())
@keen marsh :white_check_mark: Your eval job has completed with return code 0.
['__new__', '__repr__', '__hash__', '__str__', '__getattribute__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__iter__', '__mod__', '__rmod__', '__len__', '__getitem__', '__add__', '__mul__', '__rmul__', '__contains__', 'encode', 'replace', 'split', 'rsplit', 'join', 'capitalize', 'casefold', 'title', 'center', 'count', 'expandtabs', 'find', 'partition', 'index', 'ljust', 'lower', 'lstrip', 'rfind', 'rindex', 'rjust', 'rstrip', 'rpartition', 'splitlines', 'strip', 'swapcase', 'translate', 'upper', 'startswith', 'endswith', 'removeprefix', 'removesuffix', 'isascii', 'islower', 'isupper', 'istitle', 'isspace', 'isdecimal', 'isdigit', 'isnumeric', 'isalpha', 'isalnum', 'isidentifier', 'isprintable', 'zfill', 'format', 'format_map', '__format__', 'maketrans', '__sizeof__', '__getnewargs__', '__doc__', '__setattr__', '__delattr__', '__init__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__dir__', '__class__']
somewhere in your script where it will evaluate and show you the results or in a new cell if you are using a notebook
uhh
i would say that the correct way to have a list in a column in any rdbm is instead to use a separate table and to connect them together with a foreign key
i see now that i'm more or less partly is paraphrasing @paper flower here
What sort of interpreter are you using to execute your code?
im not sure
Are you writing a script in a .py file and then executing at the command line?
yeah
I tried this:
trade = mycursor.execute(f"FETCH trade FROM t_info WHERE channelID = '{message.channel.id}'")
it didn't work?
mysql.connector.errors.ProgrammingError: 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 'FETCH trade FROM t_info WHERE channelID = '925825930847477790'' at line 1
change FETCH to SELECT
please don't use f-strings or any other way to format a string when working with sql, you are opening your self up to sql injection attacks
instead use placeholders/bind variables that will protect you, like:
trade = mycursor.execute('SELECT trade FROM t_info WHERE channelID = %s', (message.channel.id, ))
oh okay
mysql uses %s as placeholder not ?
ah, my bad if it's mysql, i probably didn't read carefully enough
no worries
And You need to fetch the data after execute with fetchone() or fetchall() depending what you want.
i tried both but both didnt work
mycursor.execute('SELECT trade FROM t_info WHERE channelID = %s', (message.channel.id,))
trade = mycursor.fetchone()
The chance of SQL injection in this circumstance is slim to none tbh.
Yes, but it's better do not build up a bad habit.
it works but it just returns as None
None means no data found.
there is data in my database
can someone help me out with this question https://stackoverflow.com/questions/72279353/sum-of-all-values-in-column1-in-table1-divided-by-sum-of-all-values-from-column2
i agree with @grim vault never the less, better to learn to do it the right way and make that a habit
you could also try:
mycursor.execute('SELECT trade FROM t_info WHERE channelID = %s' %message.channel.id)
and if that still doesn't work just go back to the f-string:
mycursor.execute(f'SELECT trade FROM t_info WHERE channelID = '{message.channel.id}')
okay
Ultimately, the same way in which somebody would have to modify his code to successfully perform a SQL injection with an f-string would be the same way that it would have to be done using your "safer" method. You are still substituting the same part of the string with the same variable.
And for the record, the "right way to do it" is the way that works... it's six of one and half a dozen of the other.
i don't know how it works with that driver and in python, i must confess that i come from other languages that do not do it on the client side at all but does it using prepared statements and placeholders for proper bind variables in the database, in those cases it's not done on the client side at all and that is a big difference from doing it as you say it's being done in the driver
even if it is being done on the client side in the driver it's probably much better sanitized in the driver by it's developers then what the average python developer will do themselves
i stand by my statement that users shouldn't be using f-strings or other ways to insert variables directly in to the sql query
Interesting... that very greatly reduces the benefit of SQL embedded python scripts btw
now i don't follow, what exactly do you mean with "SQL embedded python scripts" and what benefits would be reduced in what why?
You don't gain any benefits by using f-strings there, you only introduce a possible vulnerability
If you need something more flexible to build your queries you could use sqlalchemy
Hey guys, I have a very beginner type question for yall:
I am working on a small project that involves scraping web data and putting it into a shared excel document. Since I was learning how to use sqlite at the time, I put it into an sqlite database, along with some other dated info I wanted to match it up with
My end goal is to have it running on the cloud instead of on a schedule on my own pc, and to have it uploading to some sort of database or excel document
but it seems like all my options are complete overkill. Like setting up an azure database seems way too complicated at this time right?
I just feel like there have to be easier ways of doing this but I don't know where to look or who to ask
you can still use sqlite in many cloud environment as long as they offer persistent storage
on others like Heroku you can't, they will wipe the storage quite regularly and the data will be gone, there you would have to use there there database add-on which is a postgres database that they host and run
so, as you see it can very vastly from hosting company to hosting company and even among different product offerings from the same hosting company
So something like azure would be able to hold my sqlite file in the same directory as a script?
i don't know azure well enough, but I would think it depends on which of their services you are using, if it's a normal vm with persistent storage, yes it should
Yeah, you could use Azure to create a SQL instance, migrate your data from the sqlite file to the cloud and run ADF pipelines that schedule python scripts stored as blob files to run in an Azure Batch Pool instance.
Data type mapping between Pandas and SQLAlchemy sure is... something. Having to write some pretty hefty manual datatype remapping functionality to allow for proper indexing and DB optimization.
Im pretty confused here
await cursor.execute('CREATE TABLE IF NOT EXISTS fc (guild INTEGER, channel PRIMARY KEY)')
and how will i insert a typing.List here
You can create two tables - one for guilds, second for channels (you needed a list of channels, iirc, right?)
yes, list of channels
Maybe a tutorial like this would be helpful: https://www.tutorialsteacher.com/sqlserver/tables-relations
But the main idea is to have a table linked to another table by it's id
i never used key so idk how to connect those and how to insert
Okay
You have to use foreign keys to "link" them
What you need is called one to many relationship
await cursor.execute('CREATE TABLE IF NOT EXISTS fc (id INTEGER PRIMARY KEY AUTOINCREMENT, guild INTEGER, channels INTEGER, FOREIGN KEY (channels) REFERENCES lists (id))')
await cursor.execute('CREATE TABLE IF NOT EXISTS channels (id INTEGER PRIMARY KEY AUTOINCREMENT, channel INTEGER)')
and im still confused about SELECT and INSERT part π
If you want to select guild and it's channels you can use join to join two tables
Or just select all channels where guild_id equals guild id you want
didn't you indicate that you wanted it to be a list of channels?
in that case i would make the relationship the other way around
@exotic mirage Your tables should look something like this:
create table guild (
id bigint primary key
);
create table channel(
id bigint primary key,
guild_id bigint not null references guild(id)
);
you can think of it like if a channel belongs to a guild
Hi mates, Anyone can help me better understand Error (Condition) Handlers in MySQL ?
I don't get why Handlers are bound to Stored Procedures and can not be defined elsewhere
oh thanks
I am familiar with SQL databases. I still have a verz basic question: What is the difference between NoSQL and SQL. Should I try NoSQL in my next project?
NoSQL is basically everything that is not sql: flat files (json, csv), mongodb.
Usually nosql is better for unstructured data, usually for datascience, webscraping.
SQL is better for structured, systematic data
Ok, Thanks π
hey guys do u think there could be any fix for sqlite3 module in python not finding a table that is already there
sqlite3.OperationalError: no such table: stud
- first check if you are using the same database
2 why are you using that gui interface
3 If you are using that app which i think it is then you must save the chnages first in that application before running the python program it wont commit itself.
i did all that
i use gui to show that table exists
obviously i use scriptural version
and i commited it db.close()
db = the var with refering database
Switch to the Database Structure tab and check the create table statement, maybe there is a space at the end?
note that close() is not a the same as commit(), the docs even have this to say about it:
close()
This closes the database connection. Note that this does not automatically call commit(). If you just close your database connection without calling commit() first, your changes will be lost!
https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.close
but most of the time you will be fine anyways as sqlite operated in autocommit mode by default
How to make a list for member ID? Like in the photo, but instead of Object -> member ID?
My code
actually i did commit , but wrote it wrong here
nope no spaces
i tried everything still aint working
thanks for the help everyone
π
You can NOT use parameter binding for column / table names. In this case you'll need the f-string.
Under your _id can't you just do member.id
also, in this example the f-string would be safe as the variable isn't coming from any kind of user input π
@crystal kindle
>>> import itertools
>>> result = [(10,), (45,)]
>>> list(itertools.chain.from_iterable(result))
[10, 45]
hii im new to db
and im trying to use aiosqlite for my discord bot
Any issues?
idk how to connect it and how to create one in https://railway.app/new
im reading this docs btw
I didn't use railway
sqlite database is simply a file, it's created on the same host where your bot is
im hosting on replit (pls dont judge)
They wipe storage quite frequently
You won't be able to use sqlite there, they would just delete the file
oo
this is what i found
@sly garden
"the best to use" isn't really a good query lol
they ask you to use replit-db which is as bad as json, even worse.
:/
so what do i use
cuz im not very familiar with db
i dont want to pick a gg db
try learning raw sql first, all the sql databases work same ( upto 90% ), just the way of connection and query execution differs
then you can use any online hosted database, which wont get deleted because of your replit
ok
so i learn sql?
the pins of this channel have many good tutorials, you can check them out
personally i prefer: https://sqlbolt.com
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
yea
never tried it, so wont make a comment on it
ok
hello!
I'm having an issue, where i believe it's happening due the cursor is blocked by the previous query, so when i run something else it returns an error.
Any suggestions to fix it?
def select_element(conn):
cursor = conn.cursor()
select = "SELECT * FROM production_orders"
cursor.execute(select)
return cursor.fetchone()
def delete_order(conn, id_order):
cursor= conn.cursor()
cursor.execute("DELETE FROM production_orders WHERE client_id = %s", [id_order])
conn.commit()
cursor.close()
it looks like when i execute delete_order after select_element gives an error
what's the error though?
i think i figured out the problem.
I had to save cursor.fetchone() value on a variable, then close the cursor, and return the variable at the end of select
@torn sphinx thank you
SELECT LastName, FirstName, COUNT(*) AS "OrderCount"
FROM [Order]
WHERE "OrderCount" > 15
INNER JOIN Customer ON [Order].CustomerId = Customer.Id
GROUP BY CustomerId
ORDER BY "OrderCount" DESC, LastName, FirstName```
what is wrong here
this might be a noob question, but when should i use databases?
You need it when your trying to link different types of information together. Say for example apple, when you buy something you send them your information. They then store these information and link them together in a system. So when they search you up they can find your address, and how many apple product you have bought etc.
A libary can have such a database
wouldnt it be better if its just stored into memory?
That would be too big and complicated
Every customer is given a Id which is unique, which makes it easlier to find customer fast
In the past when computers weren't as developed as now, they used to write it down on paper
damn
If you learn Sql which is basically how you make a database, you learn how to make database, insert data into it, remove data, find data just by simple lines
Yes you need to do 3 things when using it. First you import sqlite, then you make a destination for your database, and make a cursor
cool, ill look more into it, thank you
Of course, i'm as new as you. If there is anything more dm me
cur.execute('''CREATE TABLE Genie
sqlite3.OperationalError: near "Long": syntax error
new to SQL know nothing tbh
Is it possible to store data in sqlite and make sure its not erased when the program close? I've run into this error a lot
.commit()
i set the function to store data in the database then when i relaunch the app all the login details are gone and i have to start over
^^
you have to store the database file in a persistent file system
where are running your program? locally or at some provider?
what does your connect() statement look like?
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
I'm tryin to design database for educational purpose and i don't know if i'm doing good : does this design make sense ?
I tried to say a book avec 1 publishing company and a company can have books ?
that is definitely not python
is it javascript running in the browser or running under node.js, or what kind of environment is this?
No it doesn't make sense
that doesn't look right, is everything a primary key in there?
app.sqldbm.com << i use this app but i'm not confortable with it
the app just add primary key to all new colum
your pub_compagny table looks like it's spelled wrong, I would suggest that you just rename it publishers and give it an id column and make that the primary key
then have a publisher_id column in the books table that point to the id of the other table
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
@tropic plank paste your code there
and send the url
or do this
async def on_message(message):
if message.author.id == client.user.id:
return
author = message.author
guild = message.guild
async with client.db.cursor() as cursor:
await cursor.execute("SELECT xp FROM levels WHERE user = ? AND guild = ?", (author.id, guild.id,))
xp = await cursor.fetchone()
await cursor.execute("SELECT xp FROM levels WHERE user = ? AND guild = ?", (author.id, guild.id,))
level = await cursor.fetchone()
if not xp or not level:
await cursor.execute("INSERT INTO levels (level, xp, user, guild) VALUES (?, ?, ?, ?)", (0, 0, author.id, guild.id,))
await client.commit()
try:
xp = xp[0]
level = level[0]
except TypeError:
xp = 0
level = 0
if level < 5:
xp = random.randint(1, 3)
await cursor.execute("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?", (xp, author.id, guild.id,))
else:
rand = random.randint(1, (level//4))
if rand == 1:
xp = random.randint(1, 3)
await cursor.execute("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?", (xp, author.id, guild.id,))
if xp >= 100:
level += 1
await cursor.execute("UPDATE levels SET level = ? WHERE user = ? AND guild = ?", (level, author.id, guild.id,))
await cursor.execute("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?", (0, author.id, guild.id,))
await message.channel.send(f"{author.mention} has leveled up to level **{level}**!")
await client.commit()```
async def on_message(message):
if message.author.id == client.user.id:
return
author = message.author
guild = message.guild
async with client.db.cursor() as cursor:
await cursor.execute("SELECT xp FROM levels WHERE user = ? AND guild = ?", (author.id, guild.id,))
xp = await cursor.fetchone()
await cursor.execute("SELECT xp FROM levels WHERE user = ? AND guild = ?", (author.id, guild.id,))
level = await cursor.fetchone()
if not xp or not level:
await cursor.execute("INSERT INTO levels (level, xp, user, guild) VALUES (?, ?, ?, ?)", (0, 0, author.id, guild.id,))
await client.commit()
try:
xp = xp[0]
level = level[0]
except TypeError:
xp = 0
level = 0
if level < 5:
xp = random.randint(1, 3)
await cursor.execute("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?", (xp, author.id, guild.id,))
else:
rand = random.randint(1, (level//4))
if rand == 1:
xp = random.randint(1, 3)
await cursor.execute("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?", (xp, author.id, guild.id,))
if xp >= 100:
level += 1
await cursor.execute("UPDATE levels SET level = ? WHERE user = ? AND guild = ?", (level, author.id, guild.id,))
await cursor.execute("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?", (0, author.id, guild.id,))
await message.channel.send(f"{author.mention} has leveled up to level **{level}**!")
await client.commit()```
i did
@client.event
async def on_message(message):
if message.author.id == client.user.id:
return
author = message.author
guild = message.guild
async with client.db.cursor() as cursor:
await cursor.execute("SELECT xp FROM levels WHERE user = ? AND guild = ?", (author.id, guild.id,))
xp = await cursor.fetchone()
await cursor.execute("SELECT xp FROM levels WHERE user = ? AND guild = ?", (author.id, guild.id,))
level = await cursor.fetchone()
if not xp or not level:
await cursor.execute("INSERT INTO levels (level, xp, user, guild) VALUES (?, ?, ?, ?)", (0, 0, author.id, guild.id,))
await client.commit()
try:
xp = xp[0]
level = level[0]
except TypeError:
xp = 0
level = 0
if level < 5:
xp = random.randint(1, 3)
await cursor.execute("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?", (xp, author.id, guild.id,))
else:
rand = random.randint(1, (level//4))
if rand == 1:
xp = random.randint(1, 3)
await cursor.execute("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?", (xp, author.id, guild.id,))
if xp >= 100:
level += 1
await cursor.execute("UPDATE levels SET level = ? WHERE user = ? AND guild = ?", (level, author.id, guild.id,))
await cursor.execute("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?", (0, author.id, guild.id,))
await message.channel.send(f"{author.mention} has leveled up to level **{level}**!")
await client.commit()```
there we gp
there you go
now what
the error
wrong server
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
level.db
aiosqlite
Current error shows line 38
are you sure you don't close your db in any moment?
Wdym by that
Can u explain more to me
closing the connection to your db
Idk if Iβm closing it I donβt think I am
well idk, i can't see that part of the code 
Can someone help me with a SQL question
What do you guys think of this data structure?
/Sites
-----------------------------------------------
Sites posts
- id
- user_id
- site_category_id
- site_brand_color_id
- is_visible
- published_at
Sites Post Info
- id
- site_post_id
- name
- slug
- logo
- version
Sites pages
- id
- site_post_id
- site_page_category_id
- versoin
This will need to get the 'site' brand color as well, and should be able to be filtered by that.
Sites pages content (1-4 variations - shown only one record)
- id
- site_page_id
- image
- is_mobile
- is_dark
use an id for the category table too
and the book table should probably be named books (plural)
all in all it looks a lot better π
#python-discussion i cant find it so ignore this
Do u know SQL
it's really shaping up π
table names can actually be plural or singular, either is fine if you think one or the other makes more sense to you, either way you choose just keep it consistent for all tables
columns are usally in singular. so a column with a foreign key would typically be named like book_id instead of books_id even if it points to a table named in plural like books
join tables are often named like the two tables it connects but with an underscore between them
ok do you think i should populate categories with name of category like "Romance" ?
i know some sql, but not as good as some of the professional database administrators i know
if you have a question, ask it in the channel, i bet there is people in here that is better then me at sql
Whereβs the SQL channel
There is no SQL channel it falls under this channel.
Can someone help me with a join in
Also it is better to ask a question then to ask to ask a question.
ok ty π₯
you can prepopulate the table with popular categories if you want to or just add them as you need them, either way is fine but i think i would go with the latter my self in most cases to not clutter the table with unnecessary/unused entries
WITH (
SELECT BUYDATE, NAME, SUM(ORDERSIZE) AS NEW_COLUMN
FROM shopper_data sd
WHERE BUYDATE = CURRDATE() - 7
GROUP BY BUYDATE, NAME
ORDER BY SUM(ORDERSIZE) desc
) AS totalordersize
SELECT tos.*, RANK() OVER (PARTITION BY NAME, ORDER BY NEW_COLUMN desc) AS RANK
FROM totalordersize tos
I canβt figure out my error I use vertica database
Thanks for your help
my pleasure π
i never heard of or even less worked with vertica
but are you sure it shouldn't be like:
WITH totalordersize AS (
SELECT BUYDATE, NAME, SUM(ORDERSIZE) AS NEW_COLUMN
FROM shopper_data sd
WHERE BUYDATE = CURRDATE() - 7
GROUP BY BUYDATE, NAME
ORDER BY NEW_COLUMN DESC
)
...
note that i also changed the order by to use the alias
Thatβs not ranking
Anything
Rank()
i just rewrote the first part slightly, i didn't touch the last part and didn't bother to repeat it and just wrote ... in-place of that
Can someone help me with discord.py with databases
i want my bot to import info in db
How can i manage my info using dbs
When i generate key using command that key goes to database
into collum unused keys
i can seem to print things from my db
How would you lock a row to prevent reads in MySQL?
SELECT FOR UPDATE doesn't seem to do it
Hey anyone know any cloud providers where I can store any sort of database? I kinda need one in the terrabytes (5-10) and easily upscale to 20TB+
Preferably NOSQL
I would assume gcp or aws could work
what @keen minnow said and probably Azure too, and maybe Linode
first, what kind of mysql storage engine are you using for that table?
i'm guessing InnoDB
SELECT ... FOR UPDATE will block any other locking select such as SELECT ... FOR UPDATE or SELECT ... FOR SHARE but not plane SELECT ... statements without locking requests
however, you can change the isolation level set either as the default or at least for all the involved sessions to a strict level such as SERIALIZABLE and disable autocommit which will treat all select statements as if they had FOR SHARE added to them, but doing so will negatively impact the performance of your database
if you are in control of the other select statements that you want to be blocked by your SELECT ... FOR UPDATE you could change just those other select statements and add FOR SHARE only to them, then your SELECT ... FOR UPDATE will block those
https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html
together with https://dev.mysql.com/doc/refman/8.0/en/innodb-transaction-isolation-levels.html
hi can anyone help me setup influx database? i dont know how to download it
how do you want to run it, with or without docker?
if it's without docker, in what environment/os?
now i wanna set it up on windows but after i wanna run it 24/7 on linux vps prolly
Aaah, thatβs probably why, it only locks other FOR UPDATE queries. Thanks!
go to: https://portal.influxdata.com/downloads/
choose your os (or in the case of linux, the right or closest distribution, if nothing matches use the generic "Linux Binaries" for the architecture you are going to run it on) and follow the instructions that appear just under there
you can get more detailed instructions from: https://docs.influxdata.com/influxdb/v2.2/install/?t=Windows
so the only way to download it on windows is by using Docker?
or Windows Binaries
any other locking selects such as SELECT ... FOR UPDATE and SELECT ... FOR SHARE
and both of those types of locking selects will block any queries that try to change any of the locked rows in any way
but the SELECT ... FOR SHARE will permit other SELECT ... FOR SHARE statements to run in parallel while SELECT ... FOR UPDATE will not permit that
wasn't it the windows binaries you wanted?
and if you don't want to use power shell to download influxdb as per the instructions on their download page you can also get the windows binaries in a zip file from github: https://github.com/influxdata/influxdb/releases
Okay, thanks
thats what it should do?
i guess thats not good
the powershell line just downloads the zip file for you and extracts it to the folder that is specified on the command line, there's nothing more to it really
oh, your user doesn't have permission to write to that folder
you would need to run powershell as an administrator and run at least the last command with those privileges to be able to expand the archive to that directory
i have this only
okay i run the command again
and now its in the correct path i think
if you follow the instructions on https://docs.influxdata.com/influxdb/v2.2/install/?t=Windows
you'll see that you should follow up with (again in powershell as an administrator):
mv 'C:\Program Files\InfluxData\influxdb2-2.2.0-windows-amd64' 'C:\Program Files\InfluxData\influxdb'
to get it moved to the right path and then run:
cd -Path 'C:\Program Files\InfluxData\influxdb'
./influxd
just follow the linked documentation
mv command doesnt exists
ok i need to use powershell
powershell should have it
yes, i wrote that much, and again, you need to run powershell as an administrative user, or else you will not have permissions to move things stored in that systems directory
okay
and how do i make this db run?
i need to run this .exe file?
okay i guess its working since i can go to http://localhost:8086/
that's what the last command i typed does...
if you ask for help at least read what the one trying to help you has written
okay but i need to have this powershell running to not close the db yes?
What about a little cheaper Iβm just 1 dev testing something
SELECT ProductName, Quantity, LastName, FirstName, OrderNumber
From Product, OrderItem, Customer, [Order]
WHERE Product.Id = OrderItem.ProductId
AND OrderItem.OrderId = [Order].Id
AND [Order].CustomerId = Customer.Id
ORDER BY ProductName, Quantity, LastName, FirstName, OrderNumber ASC;```
I'm trying to enter a WHERE Quantity > 100
but when i put it in there it gets me an error
Where are your trying to add new condition?
Hello what would be the sql query to delete rows from table where (column1, column2) in [(1,3),(2,5),(6,3)]
delete from <table>
where (col1, col2) in ((1, 2), (3, 4), (5, 6));
π€
Yeah, that's exactly what I was looking for
Let's see if I can fit in with what I have right now
Thank youπ
I'm trying to figure that out, ive tried to put it in every single place but same error everytime
I want to put in sql WHERE Quantity > 100
SELECT ProductName, Quantity, LastName, FirstName, OrderNumber
From Product, OrderItem, Customer, [Order]
WHERE Product.Id = OrderItem.ProductId
AND OrderItem.OrderId = [Order].Id
AND [Order].CustomerId = Customer.Id
AND Quantity > 100 -- HERE
ORDER BY ProductName, Quantity, LastName, FirstName, OrderNumber ASC;
You can't have multiple where statements, you can use logical operators like AND instead
yes, unfortunately you will have to keep it running in powershell as they have not bothered to give influxdb any native windows service support, but...
there is ways to run it as a windows service anyways, you will just have to do it by hand or use third-party tools: https://github.com/influxdata/docs.influxdata.com-ARCHIVE/issues/2164
if you want to set it up your self by hand microsoft has general instructions on how to do it that you would have to tailor to influxdb your self: https://docs.microsoft.com/en-US/troubleshoot/windows-client/deployment/create-user-defined-service
or using the third-party open-source tool NSSM: https://nssm.cc/download
and some instructions on how to use it: https://web.archive.org/web/20211125170627/http://richardn.ca/2019/01/04/installing-influxdb-on-windows/#2runningasaservice
its worked nice, but idk why this is incorrect now
looks like ordering problem to me
But shouldnt i do it?
you'll find that running a database with 5-10 TB of storage in the cloud, not to mention 20 TB, will not be cheap anywhere
but smaller providers like Linode and others might be a little cheaper then some of the big names like AWS
Hey anyone on that can help m
With coding
Hey guys I've been stuck at this error for so long rn and can't figure it out it's a relation DNE.
βββ
With
INFO AS (SELECT to_char(WeekDate, YYYY-WI) as Week_Period, ordType, Count(Distinct shoppers) as names,
Sum(total)Ordertotal
From Order_data ord
Join name_reference nr using (shoppers)
Group by week_Period, ordType
Select week_period, ordType, names, ordSize rank() over (partition by ordTypr) as rank
From INFO
βββ
When you are in the Tb ranges, you are way beyond the "single dev free tier"
How do i change a value every minute?
automatically using discord.py
On sqlite dn
db
Discordpy has support for periodic tasks
can u send documentation
please
group is a reserved keyword
is there any way i could host my discord bot on my vps but use the db on my pc im using postgres
Hi guys, I'm getting this error sqlite3.InterfaceError: Error binding parameter 2 - probably unsupported type.
I believe this is the line thats causing this issue python self.cur.execute("INSERT INTO accounts VALUES (?,?,?)", (str(discordid), float(200.0), username))
And this is the table ```python
self.cur.execute('''CREATE TABLE IF NOT EXISTS accounts (discordid integer, money real, username text)''')
If you have static ip address - yes
Otherwise it would change frequently and bot would stop functioning
why are you converting discordid to string?
Also you should use biginteger instead of integer, discord ids are 64 bit wide, integer is only 32 bit
Oh okokok
I changed that but I'm still getting this issue discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: InterfaceError: Error binding parameter 2 - probably unsupported type.
You changed what?
I removed the converting and I changed it to biginteger
self.cur.execute("INSERT INTO accounts VALUES (?,?,?)", (discordid, float(200.0), username))
self.cur.execute('''CREATE TABLE IF NOT EXISTS accounts (discordid biginteger, money real, username text)''')
^its what it looks like now
Maybe it's an issue with your float value, since it reports an error with argument number 2
I think it has something to do with the float
Yeahhhh
But I'm not sure
I think the conversion from float to real isnt working
Is that the full error?
self.cur.execute("INSERT INTO accounts VALUES (?,?,?)", (discordid, float(200.0), username))
sqlite3.InterfaceError: Error binding parameter 2 - probably unsupported type.
This isnt the full error msg but I think this is where the issue lies
Hm, i'm not sure what's the issue here, did you delete your table before creating it again?
@lilac bolt
Well, you should change your tables manually then
There are migration tools for database schema like alembic but it's usually used together with sqlalchemy
Also this query should work, just tested it
Check values of discordid and username π€
Okok
Ohh maybe I need to convert discorid into int
But that has never been a problem before
Ehm, what is it then?
Earlier the way I was doing was I was inputting the values directly into it without the ???s
It should be int
Ok converting it did nothoing
Just check types of all arguments please
Also looking at the documentation i dont think bigint is a thing
I cant find anything on it
biginteger
Okok
oh.
it was username π
i needed to convert username to string
wait thats so dumb
username already was a stirng
okok
tyty for the help
type(username)
ohh........
OK TY
Also I cant find anything about bigint
And also it was working before when I was just using normal ints
So I'm a bit confused
π
My IP doesn't change very often, so I'm down to do that, it changes every month or so, how would I go onto doing that?
You'll need to configure port forwarding on your home router. Other then that, you're pointing your app to your database just like any other
Static IP is not necessary, just use no-IP
I want to learn database but I don't know where to start what do you recommend
just use integer with sqlite as it can store up to 64 bit signed integers: https://www.sqlite.org/datatype3.html
if you need bigger numbers than that or support for things like 64 bit unsigned integers with sqlite you will have to go with text and convert your numbers to strings
Ah thank you!!! @jade wing
you probably want to start with a relational database and learn SQL and the basics of the normalization levels
one of the simpler databases are sqlite, which is an embeded database and doesn't need any separate server software running
other well known and widely used databases are mysql and mariadb (that is a fork of mysql) and postgres (which is highly capable), and then you have commercial behemoths like Oracle (which now owns mysql as well)
mainly on the windows side of things you also have microsoft mssql server
all of them use a flavor of SQL
Is there any good resource for python data science?
you might want to ask in #data-science-and-ml
Oops sorry π
Is it a good idea to have autocommit=True while using aiomysql?
Idk why but after sometime of using pool object it is not working after some time!
Not sure if this is the right topic to find help with openpyxl
I have a program reading data from one row and using it as a variable in subroutine, i can print the output in terminal
I'm looking to have it write the data into the adjacent column then move onto the next one
simplified:
Taking data from cell 1B β
Running data through function β
Outputting result β
Write result into cell 1Cβ
Return to step 1, starting at 2Bβ
Trying a new method now or I'd post code, but if anyone has any advise would appreciate it. If this is the wrong channel let me know, I used the help channels but know one knew!
^^Update to above^^
column_name = 'username'
column_name2 = 'hashtags'
for column_cell in sheet.iter_cols(1, sheet.max_column):
if column_cell[0].value == column_name:
B = 0
for data in column_cell[1:]:
htag = data.value
h = Hashtag.from_name(l.context, htag)
if column_cell[0].value == column_name2:
C = 0
for cell in column_cell[1:]:
cell.value = h.mediacount
book.save
I've written this code out, however, it runs indefinitely without any errors, but also without any changes to the sheet. I am unable to see where it's going wrong as there are no errors.
is this a proper implementation of parameterized queries?
s="INSERT INTO deck_storage (id,card,amount,deck_name,game,email) VALUES(%s, %s, %s, %s, %s, %s)"
args=hold,cards,camt,deckN,game,userN
db.execute(s,args)
looks okay if that is the format for placeholders used by that database driver that you are using
can I get some help understanding databases just a little bit more to get me pointed in the right direction for my project, I am brand new her and am not voice certified yet so any help will do
If you've never touched a database before, SQLite is generally the easiest to start with. But for any sort of production grade web app you'll probably need something more powerful like Postgres
Thank you for the advice
Visit this link to see the note. Giving the URL to anyone allows them to access the note, too.
Is this correct?
hm is using f-strings for replacing table names and parameters names bad? (sqlite)
table_name = "uwu"
Cursor.execute(f"CREATE TABLE {table_name} ...")
Not sure, but I believe this is the standard way: https://www.adamsmith.haus/python/answers/how-to-bind-variables-to-a-sql-query-in-sqlite3-in-python
Python answers, examples, and documentation
I do know that works fine, I just wanted to know about table names
thanks though
i might be a bit late the pick this one up...
handling excel files in anything else then excel aren't idle even though things like google docs and openoffice has come a long way
it would be much easier to handle something like a csv file instead
if you must process an excel file you can, but the documentation for openpyxl has warnings such as:
openpyxl does currently not read all possible items in an Excel file so images and charts will be lost from existing files if they are opened and saved with the same name.
why are you processing the sheet column by column when you want to do operations per row?
you probably only want to check the column header names once and not for each iteration, so we'll start with that
you must call save with a filename as an argument and you defensively don't want to be saving the excel file for each iteration, that should be done at the end outside of the loop
instead try something along the lines of:
from openpyxl import load_workbook
filename = 'test.xlsx'
...
book = load_workbook(filename)
sheet = book['Sheet1']
# verify the names of the column headers on the first row for the first two columns of the sheet
if 1 and sheet['A1'].value == 'username' and sheet['B1'].value == 'hashtags':
# process the sheet row by row starting from the second row
# to make range() in python incluseive we need to add 1 to the index of the last row
# otherwise we will not process the last row of the sheet
for row_num in range(2, sheet.max_row + 1):
# fetch the value from column B of the current row and use it as input to the function
h = Hashtag.from_name(l.context, sheet[f'B{row_num}'].value)
# set the value for column C of the current row
sheet[f'C{row_num}'].value = h.mediacount
book.save(filename)
if there is someone else in here that knows the openpyxl library better then me they could probably write this in a better way as i have never worked with this library before now
... in the code is just where i had the code for Hashtag.from_name() and the l.context stuff to make it compatible with your code
there is no placeholders for anything else then values as far as i know, so you would need to do something like that to be able to have other dynamic parts in a sql statement
if you have to do that for your design to work you should go to great lengths to avoid using variables that come from any kind of external input
as a last resource if that isn't an option either you should take extreme care to sanitize the input data and be strict with what characters or strings you allow to go through
when sanitizing data it's best to build a filter with what you allow rather then what you don't want to allow
hm i see, thanks a lot with that
I'm trying to connect to my DB with
from mysql.connector import connect, Error
try:
with connect(
host="mywebsite.nl",
user="myusername",
password="password",
) as connection:
print(connection)
except Error as e:
print(e)
And i'm getting this
2003 (HY000): Can't connect to MySQL server on 'mywebsite.nl:3306' (10060)
Does anyone know why and how i can fix this?
no, not really, and i apologize in advance if i'm going to sound kind of harsh now, but...
there are so many nuances to this all of this to be able to encompass it all in a few bullet points like that
you are trying to touch upon so many subjects at once such as security, privacy, data access and access rights, backups and recovery, data integrity/consistency and data redundancy (and not in a high availability sense but rather along the lines of normalization)
each of the different subjects could probably fill several books on there own and will be different from product to product
there are even completely different categories of databases and you can't just do sweeping generalizations and say that they are inherently secure, private, consistent, has no data redundancy and "We don't need to create regular backups the database management software(DBMS) does this for us" (which is not even generally true, actually none of it really is depending on the context)
your code can't reach the database
without more information it's impossible to say why
here is a few things to check:
is that the right address for the database and not just the site?
is the database running?
is the database configured accept external tcp connections?
do you have the right username and password for the database?
is there a firewall of any kind blocking the traffic between where your code is running and where the database server is running?
Is aiomysql the best option for async MySQL?
The library was unmaintained up until a while ago but it seems like it's back now
I think I'd seen of another library called asyncmy but I've never used it
Alright, thanks!
Hi, I'm trying to learn asyncpg and I wonder what's the difference if I acquire a pool and then execute a query like py pool = await asyncpg.create_pool(...) async with pool.acquire() as conn: conn.execute(...) or just use pool's execute method like ```py
await pool.execute(...)
Which would be better to store product data SQL or NOSQL. The data that will be stored is product generic info and and below that product types approximately 40 types with approximately 25 attributes. More attributes and tables can be connected to the product types
@ me when replying please
If your data is relational then use sql
If you have some unstructured fields you can still use json columns for that
@molten gazelle
I have been researching this and you can use the attributes to put the relational data
Let me tell you more about what I will be doing
I have product attributes such as weight, packaging dimensions, etc.
Below that, there're types of products such as t-shirts, pants, etc.
Under each type there will be items.
For each item, there will be 25+ attributes
@paper flower
What kind of attributes?
color, size, texture...
They could be expressed in sql too π€
Yeah, I am trying to see what would be better
Most of the data is going to be pulled from some APIs and then needs to be compared and validated
I don't think nosql helps here
Why?
How would it help with validation?
I did not say it would lol
I am wanting to know which way to go
Do you mind joining #voice-chat-text-0 ?
@molten gazelle IMO you can't go wrong with SQL, i didn't use NoSQL databases really and i wouldn't put any valuable/important data into them
At least when it comes to document db's like mongo
I understand that you can't go wrong, but is this the efficient/ right way to do it?
It is giving me headache lol
Yeah, sql should be ok
Data that you described could be modelled using sql, it's not hard to do.
If i understand correctly you would have Products and ProductTypes with multiple items each with unique attributes
I'm not quite sure why you need ProductType though
if I do it with SQL then I would not need it
So essentially just products and their variations? e.g. different color, size, etc
Well yes. If for example, it is a knife then you have the handle which has the dimensions and material, as well as the blade's dimension, style count, type of steel and etc
You would probably want add some functionality that would be easier with relational databases (e.g. favorites, brands, sellers)
Also products with different properties are usually just are different products joined into some kind of group
since they would have different SKUs
So why not NOSQL like DynamoDB?
I can store those attributes in a json under attriubtes in dynamo
^
I think nosql databases have references, so they would be kind of like joins in sql
I am also planning to connect sales and returns to each product
I think that's just not the best use for nosql
to me it seems like your data is relational
But if you have a hammer everything looks like a nail
I only briefly used nosql, so i'm not the best person to ask
I see
In your opinion how big of a project is this
Is it really complicated or not
Well, it depends on how many features you need/want
I only know that you definitely can use sql for that π
There are definitely some use cases for nosql databases in case your data can fit into different documents with not so much relationships between them, but i think that's no the case for a marketplace type of project
Maybe you would have some data that could be stored in nosql type of database? It's not like you should just one or the other
But it wouldn't store say user data/profiles in nosql (just my opinion)
hi
Bro wtf
Man I am not a scammer bruh @torn sphinx
I'm new to the community and this is how I'm treated
Sad
Just sad
scammer
i saw ur stolen pfp
with your new
user
hi
i need i lil bit of creativity for a database manager
does anybody have any idea why a login and register interface would be useful on a db manager at all?
hi, i want to ask if anyone have any references/idea on how to connect a webcam into a database. the problem is i want my webcam to scan my face and directly insert the saved photo into database. tq.
Use a script to to take a pic, then convert it to binary, put the binary into the dab using an orm like sqlalchemy
To prevent people who are not registered from looking at your data
Ideally you wouldn't store images in sql databases
hey guys, is it not possible to link a key to a table that has multiple primary keys?
For example?
Since I tried linking it to a table like below through:
CREATE TABLE table (
id INTEGER,
studentname TEXT,
subjects TEXT,
PRIMARY KEY (id, studentname)
CREATE TABLE table2 (
student_name TEXT PRIMARY KEY
score INTEGER)
wait hang on, lemme fix it up
Table2 could reference table
Oh, no
Table could reference table2
table.studentname could be a foreign key to Table2.student_name
wait srry, i just realised this example doesn't work
One of the columns of composite primary keys could reference other tables
But to reference a composite primary key you need multiple columns
I hope that makes sense
CREATE TABLE areas (
sa2_main16 INTEGER,
sa2_name16 TEXT,
sa3_code16 INTEGER,
sa3_name16 TEXT,
sa4_code16 INTEGER,
sa4_name16 TEXT,
PRIMARY KEY (sa2_main16, sa2_name16)
CREATE TABLE drinkingfountains (
objectid INTEGER PRIMARY KEY,
site_name VARCHAR(80),
suburb VARCHAR(80) REFERENCES sa2(sa2_name16))
You can't reference just one of the columns of a composite PK since it wouldn't identify row uniquely
It's like something like this where sa2 is the subject of larger sa's
That won't work
And suburbs = sa2 area names
can you explain why please?
As i just said to reference a table you need it's primary key
Since it's a composite PK you need to reference both columns
In your example you might have multiple rows with the same sa2_name16
Then you don't need composite primary key?
where they only appeaer once
I don't? But each values represent the corresponding PKs in the row
I still don't understand why you need a composite primary key here
What's sa2_main16?
It's just an id number given to each area
Seems like a common error.
sqlalchemy.exc.TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30.00
My db gets pinged a few times to fetch a row, nothing serious. Currently on a freetier aws server.
Any idea how to approach this? Is it the code? The server? The db? I really don't think I have to extend this since it will be pinged more on a real server and this situation might be a nice simulation for a stressed case situation
How do you manage your connections?
and sa2_name16 is the area name
Consider using surrogate primary keys
Like autoincrementing integers, uuids, etc
I'll paste my db main code in a min
Also i'm asking about a different column - sa2_main16
I'm not very familiar with sqalchemy specifically, but are you sure you're closing your connections after using them?
Yeah, so sa2_main16 is the id of the city, and sa2_name16 is the name that correlates to the city id
If it's just an id then can't you have a primary key just on that id?
You don't need a composite pk here
import os
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Set Database connection:
SQLALCHEMY_DATABASE_URI = f"postgresql://{os.environ['POSTGRES_USER']}:{os.environ['POSTGRES_PASSWORD']}@{os.environ['POSTGRES_HOST']}:{os.environ['POSTGRES_PORT']}/{os.environ['POSTGRES_DB']}"
engine = sqlalchemy.create_engine(
SQLALCHEMY_DATABASE_URI,
)
Set Database session settings:
SessionLocal = sessionmaker(
autocommit=False,
autoflush=False,
bind=engine
)
Base = declarative_base()
ok, but how do you create your sessions?
Where should I do this?
According to its documentation, you can use a with statement for the session/connection, which will ensure it gets closed. See the examples here https://docs.sqlalchemy.org/en/14/tutorial/dbapi_transactions.html
from sqlalchemy import Column, DateTime, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from ..configs.database import Base
from datetime import datetime
class hspDB(Base):
__tablename__ = "hspβ
β¦
In router:
hspDB.metadata.create_all(bind=engine)
Set DB dependency
def get_db():
db = SessionLocal()
try:
return db
finally:
db.close()
You're returning db, not yielding it
Also just use with
def get_db():
with SessionLocal() as session:
yield session
This worked for me in production π
Can you please explain? Whatβs the difference? I do remember following a tutorial that included yield, but then replaced it with this
You should read on context managers π€
If it's done like that then I believe the function will need the @contextmanager decorator, right?
I recall doing something very similar for shelve
But basically fastapi would execute your code until yield and then code after yield when your endpoint is done
Fastapi doesn't require you to have @contextmanager decorator
Ah okay, not familiar with fastapi
But it works the same way
Didn't realise this was even for fastapi
@contextmanager
def my_context_manager():
print("Hello")
yield 42
print("World")
with my_context_manager() as number: # Hello
print(number) # 42
# World
Contextmanagers are used to do some setup/cleanup without you having to remember to call .close or similar method
sqlalchemy sessionmaker is already a context manager but fastapi requires you to have a function to work with DI, so you end up with something like this:
def get_db():
with SessionLocal() as session:
yield session
ohh thanks!
Im just not sure what yield has to do with closing the database
I understand now, today i learned what are generators within python. Thanks Doc!
What is the use of the yield keyword in Python? What does it do?
For example, I'm trying to understand this code1:
def _get_child_candidates(self, distance, min_dist, max_dist):
if self._leftch...
Hello I'm reading an sql table and storing the content into a pandas df. I excluded PK column from the dataframe establishing a condition in order to update PK key values given a tuple of tuples containing PK values. Now I would like to update every single column for those primary keys that match the condition:
update_query = f"""
UPDATE {self.schema}.{self.table_name}
SET
/* Grab values from df */
WHERE (user_id, author_id)
IN ((1,5),(6,8));
"""
hello, how do i print the number of rows returned by a select query?
So I've been reading up on relational theory a bit and I think I don't really get what a primary key is. Is it just a key (candidate key) which was chosen as the 'cool key' by convention?
A table can have many candidate keys but only one of these can be the primary key.
How it is possible to fasten AES-256 to sqlite3?
Right, but what makes the primary key special?
Every key uniquely identifies a tuple, as I understand
Primary key cannot be null
SQLCipher?
Yes but only one of those can be a PK. They are all candidates for a PK, but you can only pick one.
does it necessary give an error when selecting a value from an empty table, or it returns "None"?
If the column you select does not exist then you will get an error.
Hey guys, if the area_id are the PK for each of the table, what should be the foreign keys then? I also have another table that has another area_id but it's for a much larger area, and another table that has an area_name of a smaller area than those of neighbourhoods and businessstats. I'm really confused as I thought that area_name could be a foreign keys but errors keep popping up
the select is locked in the loop, and it's selecting values from due_date, but not every day is including , but not all days are included, so in those days it should return None.
@proven arrow
thank you!
So how is it special? Why even have the concept of primary key?
Can multiple rows have the same area_id ? The name of the column suggests it should not be a PK.
To identify uniqueness of each row. 1NF.
help me please
There are a few options if you Google it, here's one: https://utelle.github.io/SQLite3MultipleCiphers/docs/ciphers/cipher_sqlcipher/
SQLite3 encryption extension with support for multiple ciphers
Thank you!
Nope, there's no duplicates for any area_id
π
But any key uniquely identifies each row.
Unique columns can still have null values.
Therefore in some cases you canβt identify. And so when it comes to referential integrity you canβt reference such rows.
Maybe your question is better asked what is difference between primary key and unique key. Should be plenty of answers online with more detailed explanation.
This is not always true, some DBMS allow it, some don't
But it appears that if the Foreign keys isn't a subset of the main table, then it's an error?
I think the question is why would you choose one key over the other candidate key
I want to connect to a database which is not in the same network as my computer
But the problem is the database server is not reachable through the internet
How can I do it please ?
You can't
either it needs to be made reachable through the internet, or you need to connect to it locally
how to return largest values from orders if there is two same value of orders then return orders with smallest id and largest orders? - MySql
table: STORE | Columns:
ID, ORDERS
1 , 991
2 , 32
3 , 383
4 , 991
Thank you for the reply
Any hint how i can make it reachable through the internet ?
I don't know, why isn't it reachable? Firewall? NAT?
It is located in another network. And right now I cannot put myself in the network
U need permission to access to this particular private network... Probably u need to be whitlisted before access and also credentials for vpn
does this work?
cursor.execute(f"INSERT INTO Accounts (Username, Password) VALUES ({USER},{PASS}")
which database and database connector/driver are you using in python?
Whenever i try this, i get the error:
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "c:\Users\user\Desktop\Discord Bot\Ticket System\main.py", line 939, in on_message
mycursor.execute(f"UPDATE t_info SET user_added = 'Yes' WHERE channelID = '{str(message.channel.id)}'")
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\mysql\connector\cursor_cext.py", line 243, in execute
self._cnx.handle_unread_result()
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\mysql\connector\connection_cext.py", line 794, in handle_unread_result
raise errors.InternalError("Unread result found")
mysql.connector.errors.InternalError: Unread result found```
```mycursor.execute(f"UPDATE t_info SET user_added = 'Yes' WHERE channelID = '{message.channel.id}'")```
i think it's because you are reusing the same mycursor that you have used for a previous query without reading all the results from that query before you try to use it again, mycursor.reset() should fix that for you
instead try (bonus: this is a better way to write queries then with f-strings):
mycursor.reset()
mycursor.execute('UPDATE t_info SET user_added = %s WHERE channelID = %s', 'yes', message.channel.id)
If there's no VPN you can use to get to the local network, you're out of luck
discord.errors.ExtensionFailed: Extension 'cogs.economy' raised an error: ImportError: cannot import name 'cursor' from 'psycopg2' (C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\psycopg2\__init__.py)
how can I fix this error ? I am using a sqllite3 database
Hi, I'm using async-sqlalchemy and I can't get the delete statement to work correctly, any idea why?
async def delete_user(self, model_name, user_id) -> None:
async with self.session() as session:
query = delete(self.models[model_name]).where(
self.models[model_name].user_id == user_id
)
await session.execute(query)
await session.commit()
discord.errors.ExtensionFailed: Extension 'cogs.economy' raised an error: ImportError: cannot import name 'cursor' from 'psycopg2' (C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\psycopg2\__init__.py)
how can I fix this error ? I am using a sqllite3 database.
And I don't need to send a link to the python documentation. I don't understand this stupid documentation
Error says psycopg2. Thatβs not a lib for sqlite. Itβs for a whole other database. Do you know what you are using ?
I'm not experiencing it!!!
I donβt understand what you mean. Use the correct library for your database, and that should solve your problem.
as @proven arrow already said, psycopg2 is for a database known as Postgres or PostgreSQL
if you want to use sqlite3 (only one "l" in there) you should use that library instead of psycopg2
Seems like it should work, what's the problem?
No error, that's whats bugging me
Executes correctly
But entry on db remains as if nothing had happened
Maybe it doesn't satisfy your where condition?
Try using select instead of delete to see what you're retrieving from db π€
async def fetch_user(self, model_name, user_id):
async with self.session() as session:
query = select(self.models[model_name]).where(
self.models[model_name].user_id == user_id
)
result = await session.execute(query)
scalars = result.scalars()
...
My select method works under the same logic
This is how the setup looks
DATABASE_URL = "sqlite+aiosqlite:///bot.db"
engine = create_async_engine(DATABASE_URL, future=True) # echo=True
async_session = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
async def db_init():
async with engine.begin() as conn:
# await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
So did it return anything?
Yes, this is all running through a discord bot so when I request the info its being given to me just fine but the delete statement executes and does nothing
I'm stating to think this might noy have anything to with the db handler itself
What's self.session btw?
Is the async session that I defined up there
this one
I made a class to handle db functionality
so just
self.session = async_session?
Is it an AsyncSession or a sessionmkaer?
Is a sessionmaker that uses an async engine
Hm, delete should work
You can try using async with self.session.begin() as session:
which would automatically commit your transaction π€
Also i think delete should return amount of affected rows, you could also check that
@silk elk so?
I'll take a look at it later, I have to go now. Tnx for the help
where can I learn the basics of SQL? I wanna write some data (strings, integers, lists) and read (strings, integers, lists) in SQL, nothing advanced tbh
help is much appreciated
Is there a specific database system you are going to use? MySQL, PostgreSQL, Microsoft SQL Server, etc?
https://sqlbolt.com/ is good for learning sql
Is this correct? tia.
Select all the unique values from the Album column in the Artists table.
SELECT DISTINCT Album FROM Artists;
Display full names of publishers with whom the author Alfred Aho did not publish his book(s). Your
query must use EXISTS (/NOT EXISTS) clause.
select publisherfullname from publisher join Published_By pu on publisher.PUBLISHERID= pu.PUBLISHERID join written_by wr on pu.bookdescID=wr.bookdescID join author on wr.authorID=author.authorID where not exists(select authorID from author where firstname='ALFRED' and lastname='AHO');
is this correct
yeah, looks good π
Even w3schools would do
Any DBeaver experts here? I somehow removed the blue "Read Only" lock icon from my toolbar. Right click and "Restore Hidden Toolbar Entries' does nothing. I can still toggle with the Database menu but that's annoying π
is this ok to learn basic SQL?
MySQL tutorial for beginners - Learn MySQL, the world's most popular open source database.
π₯ Want to master MySQL? Get the full MySQL course: http://bit.ly/2uAoPM3
π Subscribe for more SQL tutorials like this: https://goo.gl/6PYaGF
βοΈWant to learn more from me? Check out these links:
Courses: https://codewithmosh.com
Twitter: https://twitter....
Anything would be fine, but you need to do some projects using it too
yeah I need to learn it for a project π
but don't try to learn it by just reading or watching, you should learn by tinkering with it and trying things out while you are reading or watching the material
Are you going to be using MySQL specifically? The different flavors of SQL are pretty similar but not identical, so just keep that in mind
Also, I like interactive tutorials for the basics, and they're are plenty of good ones for SQL... Datacamp, Dataquest, sqlzoo, whatever you pick is not important just keep practicing
Hi, I am beginning to learn SQL as well. Should I go with PostgreSQL or MySQL, I am not really sure which one would be useful for data science and PM roles?
Secondly, what's the best software to use for that?
What exactly are the differences between the two, except the 'case' difference? I am completely new to this.
postgres is the more advanced and capable, but mysql isn't bad either, both are very common out in the wild, mysql might be a little easier of the two
but i belive postgres can handle bigger volumes of data better and has support for more diverse data types and more languages when writing code that is executed in the database such as custom functions and store procedures
I see. Thank you so much!
And also which software/platform to use for this (online/offline)?
PUT test_index
{
"mappings": {
"dynamic": "runtime"
}
}
what will this do in elasticsearch?
to use in what scenario?
you can run either locally, self host on a server or as a managed service in the cloud at several different providers, and what you choose is dependent on a lot of factors
yall my brain is mush. I can't figure out how to write this stupid SQL query.
I have a large table, the 3 relevant columns are (FOO, BAR, BAZ). There is a 1 to many relationship between FOO and BAR. And every BAR has an attribute BAZ that is either YES or NO.
Example:
FOO | BAR | BAZ
fooA | barA1 | NO
fooB | barB1 | YES
fooB | barB2 | YES
fooC | barC1 | NO
fooC | barC2 | YES
...
I would like to find all FOO who have at least on BAR with BAZ equal to YES and bar with BAZ equal to NO
That is in this example only fooC would fullfill that
and you have no choice then have the data like that in one table?
because one-to-many relationships are typically modeled with two tables and a foreign key
and which database engine are you using?
to know the dialect and possible constrains there are
But yeah I agree
i think one would need to do a self join in this case to solve it if it's just one table
Yeah, preferably the tables should be normalized but I don't have the resource (time) to do that right now. It's really for BigQuery. I used the INTERSECTS function and that worked for me
so, you already solved it then?
yeah, brain is mush, but I managed to get there in the end haha
took me 20 min for a simple query like that tho haha
another way that i think would achieve the same and doesn't even consider the BAR column: http://sqlfiddle.com/#!5/a04131/1
cool
just an example of the self join I was talking about
one can use other join syntax as well
hey everyone , i recently started web dev and received few MONGODB files from my professor, he wants me to figure something out, i have very less knowledge about MONGODB , the problem is i am unable to find the main DB files in 1000s of files its just lost, can you tell me the what path it could be in most prolly !! HELP !!! dm me or @ me here pleaseeeeeeeeeeee !
I am using mongodb and when I started to load a list of all users this list stopped and no one else is loaded and the bot is not responding to commands either
Simply put, the bot stopped uploading new users to the database
so you received a few files from your professor, then added those to the 1000s of files on your computer ? If so, did you try checking the e-mail for the file name(s) and then searching for the name(s) in File Explorer ?
cursor.execute("create table anime(id integer primary key, name varchar(1000));")
cursor.execute(f"insert into anime(id, name) values(%s,'%s')"%(2,"testing"))
it creates but doesnt inserts mysql
is it something that i am doing wrong
even if it works now i would recommend changing it to something like:
cursor.execute("insert into anime(id, name) values(%s, %s)", 2,"testing")
```which is much safer without f-strings
Hey! No idea if this is the right channel to ask. Basically I am attempting to setup some custom middleware that will allow my Django app to run even if my Azure Redis instance is down. Currently if anything is amiss (URL, port, etc.) rather than just falling back on not caching it errors the entire app. Any ideas? Thanks!
If this is totally the wrong spot to post this Iβm sorry
What are these details changing? You don't want that to happen.
I've not used Redis personally but there's this if you need it: https://redis.io/docs/manual/scaling/
Oh itβs more of a dummy proofing situation Iβm working on, (URL put in wrong by another dev) but basically if Redis is down then the django app itself errors out on a ConnectionError exception. Iβm just trying to have it skip using Redis in the settings.py CACHE dict and use the dummy one (so it wonβt cache at all)
maybe creating a custom cache by inheriting from RedisCache and overriding some of the methods in it?
get, set, delete...
there are quite a few in #web-development that knows django really good that might be able to help you
So i made a library which basically acts as a perm number counter, now when i install this library from github and run it, instead of it using the database in the library it creates its own in the folder that im using the library in, how can i fix this
i'm guessing you are using sqlite and the sqlite db file ends up in the same dir as the script instead of the one in the dir of your lib, have i understood the issue your facing correctly?
yes correct
aiosqlite
but same thing
basically, yes
you should be able to fix your problem by in your library doing something like:
import os
from pathlib import Path
def db_file(filename):
return Path(os.path.dirname(os.path.abspath(__file__))) / filename
```and then call the function when you open the database like `sqlite3.connect(db_file('my_lib.db'))` or whatever your sqlite database file is named
with that code paths should also be handled independent of os
note that the code in the bigger code block should go within your library, not the script that you are calling your library from
yes im aware
here is my file tree
Code,
is there something that im doing wrong
hey is anyone here?
just gonna leave this here :)
Hello, how can i make an object inside of an object in TinyDB if anyone has an idea?
can you INSERT NULL in your database?
like if you have nothing to insert it will give an error
to avoid that you have to INSERT NULL right?
what database
you should be able to do ```sql
INSERT INTO my_table DEFAULT VALUES
there's more than one kind of sql db
postgres, mysql, sqlite
you should be able to do this then
but like
cur.execute(f'''INSERT INTO genie VALUES ("{date}", "{user_id}", {trade_id}, "{pair}", "{timeframe}", "{side}", {order_price}, {tp_min}, "{tps}", {sl}, {rr}, "NULL")''')
I've this. do you see the NULL
that will be NULL text
or NULL
like nothing
just put null
yeah you need to specify the columns you want to insert
INSERT INTO my_table (column_1, column_2) VALUES (value_1, value_2)
aaaaah
also