#databases

1 messages Β· Page 125 of 1

radiant elbow
#

πŸ‘

lucid needle
#

i installed aiosqlite3

#

but i cant import it

#

i am using vsc

#

and it says its unable to import aiosqlite3

granite oasis
#

What is fast way to remove large amounts of data from a SQLite3 Database. I tried to look online to no help.
Is there a way to bulk remove? like to bulk add to a database using 'executemany' eg. cursor.executemany(sqInsert, recordList)

Im working with a database of 8BG. 3.5mill lines need to be removed from a total of 49mill lines. Here is the inside of the dataTest.db
https://i.imgur.com/2AyGf8x.png
https://i.imgur.com/vRWszH4.png

listToSkip = []

def readToSkip():
    sqConn = sqlite3.connect(f'dataTest.db')
    cursor = sqConn.cursor()
    data = cursor.execute("""SELECT line_skip FROM Skip""").fetchall()
    for i in data:
        listToSkip.append(i[0])
    cursor.close()

readToSkip()

logging.info(f'Done Load. Size to remove: {len(listToSkip)}')
#>>>INFO:root:Done Load. Size to remove: 111

def delLine(line):
    cursor.execute(f"DELETE from Train WHERE line_skip={line}")
    sqConn.commit()
    logging.info(f"Del Line {line}")
    # >>>INFO:root:Del Line 24, ext,ext


sqConn = sqlite3.connect(f'data.db')
cursor = sqConn.cursor()
for line in listToSkip:
    delLine(line)
cursor.close()
radiant elbow
#

if that's still not fast enough, the next step would be to run fewer statements, and have each one delete multiple rows, using where line_skip in (1, 2, 3, 4, ...) or where line_skip=1 or line_skip=2 or line_skip=3 or something like that

#

also, make sure you have an index on line_skip

granite oasis
#

@radiant elbow

for number, line in enumerate(listToSkip):
    if number % 1000 == 0:
        sqConn.commit()
    delLine(line)

then for your second Part I could use something like this

# in def delLine(line):
toRemove = len(listToSkip)
listToSkip= listToSkip[toRemove:]
for the ? ? ? places 
#

will that work?

radiant elbow
#

yes, though you'd need to have exactly as many ? placeholders as items in the list, which is annoying but doable

pseudo summit
#

Do it all in one statement with WHERE IN and sub select.

Unless your dB supports join in where clause of delete. Not all do.

radiant elbow
#

I'd just do the "only commit after every 1000 (and right before closing, don't forget that or you'll miss the last partial batch!) and see if that's fast enough.

pseudo summit
#

Sql will do it faster than python.

radiant elbow
#

yes, definitely - but that requires more changes from what they already have.

pseudo summit
#

So I’d avoid looping in python

radiant elbow
#

this isn't a huge number of rows - it's only a few million. Python will be slower at it than SQL, but I'd still expect it to only take a few minutes.

#

you can see if I'm right: move the commit out of the inner loop, only commit once every 1000 deletes, and print the amount of time since the last commit. That'll let you quickly figure out how long it will take to do all 3500 commits, and whether or not you need a faster solution.

granite oasis
#

I had a 10BG file that I needed to remove Non english from it then put it back into a .txt. So I used python to do this

pseudo summit
#

Just saying that there’s no need to select then loop.

DELETE FROM Train WHERE line_skip IN (SELECT line_skip FROM Skip)

radiant elbow
#

ooh, you're right

#

I missed that the set of rows to delete was already coming from a query

#

that changes my mind entirely; your approach is both easier and faster.

#

I was picturing needing to build up a temp table with all the rows to delete or something, which would have been much more work.

granite oasis
#

here is my code to remove non english text

#

took 3min when using a db

#

I have 2 databses

#

Have to remove from both

#

so lines are equal

#

@pseudo summit The list is coming from another DB

#

its not of the same DB

pseudo summit
#

Ah!

#

I rescind. πŸ€ͺ

granite oasis
#

Also using

    if number % 1000 == 0:
        sqConn.commit()
``` does not speed it up
#

have to use the placeholders

radiant elbow
#

how long does each commit wind up taking, out of curiosity?

#

and you did remove the commit that was right after the delete, right?

granite oasis
#

checking

#

yes

deep rover
#

I'm having trouble rn

cursor.execute("UPDATE sespot SET (status = ? AND time = ?) WHERE (status = ? AND time > ?)", ('taken', 0, 'free', 60))

It returns an error: sqlite3.OperationalError: near "=": syntax error

granite oasis
#

@radiant elbow 99% of the time is taken by
cursor.execute(f"DELETE from Train WHERE line_skip={line}")

radiant elbow
radiant elbow
granite oasis
#

I dont how do I add that in sql3

radiant elbow
#

CREATE UNIQUE INDEX by_line_skip ON Train(line_skip);

deep rover
#

Also I tried py cursor.execute("SELECT * FROM sespot WHERE status = ?", ('free',)) fetch = cursor.fetchall() print(fetch)
It gave me
[]
This is a '[]' string right

radiant elbow
#

no, it's an empty list

#

fetchall() always returns a list of matching rows.

granite oasis
#
listToSkip = []


def readToSkip():
    sqConn = sqlite3.connect(f'data.db')
    cursor = sqConn.cursor()
    data = cursor.execute("""SELECT line_skip FROM Skip""").fetchall()
    for i in data:
        listToSkip.append(i[0])
    cursor.close()

readToSkip()

logging.info(f'Done Load. Size to remove: {len(listToSkip)}')

def delLine(line):
    cursor.execute(f"DELETE from Train WHERE line_skip={line}")
    logging.info(f"Del Line {line}")

sqConn = sqlite3.connect(f'dataTest.db')
cursor = sqConn.cursor()
index = 'CREATE UNIQUE INDEX by_line_skip ON Train(line_skip);'
cursor.execute(index)



for number, line in enumerate(listToSkip):
    if number % 1000 == 0:
        sqConn.commit()
    delLine(line)
cursor.close()

Traceback (most recent call last):
File "R:/Ai Bot/dataCleaner/readfile Remove.py", line 43, in <module>
cursor.execute(index)
sqlite3.OperationalError: index by_line_skip already exists

deep rover
#

Because later after that I tried py if fetch is None: etc the etc part not working

radiant elbow
radiant elbow
deep rover
#

Ye I aware of that. I want the bot to do something when there are no rows

radiant elbow
deep rover
#

Oh thank you

granite oasis
#

@radiant elbow

sqConn = sqlite3.connect(f'data.db')
cursor = sqConn.cursor()
index = 'CREATE UNIQUE INDEX by_line_skip ON Train(line_skip);'
cursor.execute( index )
cursor.close()

cursor.execute( index )
sqlite3.IntegrityError: UNIQUE constraint failed: Train.line_skip

radiant elbow
#

adding the index has made the database maintain a list of all rows in the table sorted by their line_skip value. Now, when you want to find one of them to delete it, it can quickly find that row by binary searching. Think of a dictionary: you want to find a word, so you flip the book open to somewhere in the middle. You check whether the word you're looking for is alphabetically before or after the words for the page you're on and you either flip to a page in the half of the dictionary before or after the page you originally flipped to, and you keep cutting down the search space until you find the page you need.

#

hm. on that database, line_skip isn't unique - there are multiple rows with the same line_skip value

#

if that's an expected condition, you can just drop the word UNIQUE. If that's not expected, you need to clean up your data.

granite oasis
#

is this the reason?

radiant elbow
#

no. try doing select * from train group by line_skip having count(*) > 1

#

actually, make that:

select * from train where line_skip in (select line_skip from train group by line_skip having count(*) > 1)
granite oasis
#

im bad with sql how do I print that statement

radiant elbow
#

if you're doing it with Python, you can do:

conn = sqlite3.connect('data.db')
cursor = conn.cursor()
query = 'select * from train where line_skip in (select line_skip from train group by line_skip having count(*) > 1);'
cursor.execute(query)
for row in cursor.fetchall():
    print(row)
granite oasis
#

that worked and fixed the issue

radiant elbow
#

what do you mean "fixed the issue"? It should have printed out a list of rows that violate the uniqueness constraint and stop you from being able to add the unique index.

granite oasis
#

yeah and now it runs

#

does the UNIQUE INDEX be stored in memory? I know .fetchall() does and make things run way faster

radiant elbow
#

no, the reason an index makes things faster is that it helps the database find the rows that are being affected.

#

and fetchall() usually makes things slower, not faster. Reading the entire result set into memory means you can't start processing any rows until all of them are available.

granite oasis
#

@radiant elbow Thanks a lot for the help and knowledge. I help me learn a lot and understand DB more

vivid delta
#

I am getting pgconfig error while executing my postgres script on a server, I searched guthub and it says to bump pgproto, can anyone give me an idea about it?

torn sphinx
#

How do I know when I should use a database

#

vs a CSV or JSON file

#

I need a simple list of accessible data to hold user accounts.

#

for a discord bot.

#

thing is a JSON file seems ideal besides being slow once I get say... 10000

#

Is their any magic database that is easily accessible and read/writable like JSON but faster?

vivid delta
#

There are various databases which are better than JSON, for eg SqLite3, MySQL, Postgres, etc.

torn sphinx
#

What would you recomend? I know nothing about databses

#

Heard bad things about mysql

vivid delta
#

Well depends on the project, I recommend Postgres but learn basic SQL before you go for it πŸ™‚

torn sphinx
#

ok.

runic mirage
#

what's data type for prefix in MySQL?

proven arrow
runic mirage
#

like i want to change prefix for bot but its in not update

#

DataError: 1292 (22007): Truncated incorrect DOUBLE value: '!'

proven arrow
#

Use a text type like char

runic mirage
#

i use varchar

proven arrow
#

That's fine also

runic mirage
#

after that its happen

proven arrow
#

Where is the error happening? Show the query

runic mirage
#

def update_prefix(cursor, dbs, prefix, updated_by, server_id):
    cursor.execute('update prefixes set prefix = %s and updated_by = %s where server_id = %s',(prefix, updated_by, server_id))
    dbs.commit()```
#
Ignoring exception in command prefix:
Traceback (most recent call last):
  File "/home/bl/.local/lib/python3.8/site-packages/mysql/connector/connection_cext.py", line 504, in cmd_query
    self._cmysql.query(query,
_mysql_connector.MySQLInterfaceError: Truncated incorrect DOUBLE value: '!' ```
proven arrow
#

And can you show the table structure for it

proven arrow
runic mirage
#
def create_table_prefixes(cursor):
    cursor.execute('''CREATE TABLE IF NOT EXISTS prefixes(
                                Num int AUTO_INCREMENT,
                                server_id varchar(255),
                                prefix varchar(255),
                                updated_by varchar(255),
                                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                                PRIMARY KEY (Num))''')
#
    async def prefix(self, ctx, *, prefix='db.get_defualt_prefix(self.bot.cursor)'):
        db.update_prefix(self.bot.cursor, self.bot.dbs, prefix, ctx.author.id, ctx.guild.id)
```  its in cog
torn sphinx
#

I think I will use sqlite

proven arrow
#

@runic mirage Right so the error is becahse your update statement is incorrect

torn sphinx
#

lol

proven arrow
#

When you want to update multiple columns, you seperate it by a comma. You have done it by AND

proven arrow
runic mirage
#

thanks dude it's work

torn sphinx
#

lmao thats amazing

river vortex
proven arrow
#

It'll be a floating point number

river vortex
#

Ohh...Got that...

#

Another question

proven arrow
#

It'll make a unique constraint on the combination of those 2 columns

#

So, for example
1,2 is a pair and so 1,2 combination can't exist twice. However 2,1 combination can occur (but only once)

river vortex
#

Got that...Thanks a lot...

boreal niche
#

Does anyone know how to set the default type to a column when creating a table?

copper sparrow
#

i’m looking at making a form for entering details the same as entering information through html, php and phpmyadmin but im not sure how to do it via bluetooth

snow imp
#

im using sqlalchemy mixed with discord.py and i want to send the primary key to the person who does the command of their object in the db how do i do this?

analog trellis
#

what is the best way to represent a task that repeats every day in a database? for example, task: read 10 pages a day. the task spans 50 days for example and I want to store data on every individual day's progress? what would the models be like? i am using django but a normal sql example is fine, I am just wondering what the relation would be

bright hound
#

Hello. I'm new to developing in general and I'm trying to set up a database for a stock trading bot. I'm using QuestDB and so far I've downloaded their tar.gz file and ran the command they specified to unpack it, but it all unpacked to the download folder where the tar file was. I'm wondering if that's not ideal, because it seems to me like I'd want those files in a more permanent place on my computer. Total beginner question but I'm brand new to this. Any help is appreciated

#

To clarify, the setup involved extracting the file with the -xvf command from the command line and I think it also installed something when it extracted it. I'm wondering if I can move those files now or if that would break something

#

Or if I need to do it over in the directory where it should be installed

finite perch
#

You should be fine moving the extracted folder anywhere you want, about the installation part ... did it 'install' in the same directory where it was extracted to?

bright hound
#

I'm not sure, lol

#

Sorry I'm not familiar with these tar.gz files so I'm not sure what happened when I ran that command

tender shadow
#

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword"
)

print(mydb)```
#

pls help i dont know what to put here it says it cant connect to the sql server 😦

#

i just started learning SQL so pls be patient with me

#

im not sure it just told me to type this

#

ohhhh

#

where should i put that?

#

inside or after?

#

like should it be inside mydb?

#

thanks man

#

sorry hehe...

white jungle
#
DBQ.query("INSERT INTO member_table (clan_id, member_id, join_date) VALUES (?, ?, ?) ON CONFLICT(clan_id, member_id) DO UPDATE SET join_date = ? ;",       [ctx.guild.id, member.id, datetime.now(), datetime.now()])

gives an error for the "ON CONFLICT"
version of python is 3.6.6. I think 3.6.6 has an updated enough version of sqlite3 to use " on conflict". can anyone assist?

#

sqlite3.sqlite_version spits out 3.28.0 so it should be able to use on conflict...

#

oh nvm.. 3.6.6 has 3.21.0 of sqlite.. i was in my 3.8 python version

keen sundial
#

Suriyawong'); DROP TABLE messages; --

calm prawn
#

How can I add date in a google database
In google docs example it said it as
data = {"date":datetime.datetime.now()}

#

But I am getting syntax error

keen sundial
#

What does the syntax error say and where is the documentation you are reading?

#

my first guess is that the document wants json so you may need to run json.dumps(data) before sending it

velvet coyote
#

Hey so if i have a .sql file, is there a way to execute that file and the stuff within that file in a postgres db?

fallow dove
#

Pretty sure postgres has cli that'll do that.

fallow dove
torn sphinx
#

Every built-in module that can be used for making mini databases:

json
csv
pickle
shelve
marshal
dbm
elder karma
#

is there a way to do insert or ignore into table with foreign key violations in sqlite?

#

i know it doesn't allow for on conflict clauses for FKs but i really want the FK to just limit what data can be inserted not roll back an entire multi row insert over a FK violation.

glossy tusk
#

Need company for studying..

trim acorn
#

Hey guys, sorry if i'm interrupting anything. Does anyone here have a DB certification? Is there any value in getting it? So far all of my google searches have brought up Microsoft sql server. Any advice would be greatly appreciated

torn sphinx
#

can somone teach me how to use mysql

#

in python

warm sphinx
#

i have a similar need

#

i need help using the mysql connector in python

#

@torn sphinx can you lmk if you find out?

torn sphinx
#

@warm sphinx uh

#

ill see

warm sphinx
#

well you'd probably need to use mysql connector too actually

torn sphinx
#

yeah

warm sphinx
#

how do you find the user

#

like i forgot what i put in for user and password

#

in mysql still

whole niche
#

how do i setup a database for strikes? dead

#

^discord py

elfin talon
elfin talon
trim acorn
#

@elfin talon Haven’t really found an answer. I have come across different ones like certified sql developer or db admin.Not sure what the benefits are of getting one vs the other.

sick nacelle
#

First time working with aws and redshift and wasn't sure if I should ask here or one of the help channels

whole niche
#
@client.command(aliases=['s'])
async def strike(ctx, member: discord.User = None, reason='null'):
                warnid = random.randint(9000000000, 12000000000000)
            post = {
                "guild": ctx.guild.id,
                "member": member.id,
                "warnid": warnid,
                "moderator": ctx.message.author.name,
                "reason": reason,
                "date": str(ctx.message.created_at)
            }```
warm sphinx
#

@uneven elk (feel free to @) you responded to my thing abt databases but i didn't get to respond
basically i have created a database and i need to find the parameters user and host
i forgot what they are

#

also sorry for double ping

torn sphinx
#

how can i connect to a sql database

#

?

torn sphinx
#

Can I connect my mongodb database to GitHub?

velvet coyote
#

Could someone give me an example of creating a connection pool in asyncpg.

#

I don't understand the example in the docs.

torn sphinx
#

QQ about the pinned message about SQL injection

#

How would I do that for mass populating

#

cursor.execute("INSERT INTO messages VALUES ("\
                        f"{int(message.id)},"\
                        f"{int(message.channel.id)},"\
                        f"{str(message.channel.name)},"\
                        f"{int(message.author.id)},"\
                        f"{str(message.author.name)},"\
                        f"{str(message.author.status)},"\
                        f"{str(message.author.mobile_status)},"\
                        f"{str(message.author.desktop_status)},"\
                        f"{str(message.author.web_status)},"\
                        f"{str(message.author.bot)},"\
                        f"{str(message.author.nick)},"\
                        f"{int(message.guild.id)},"\
                        f"{str(message.guild.name)},"\
                        f"{str(message.clean_content)},"\
                        f"{str(message.created_at)}"\
                        ")")

#

I don't need to int/string convertions but it can't hurt besides possible a very slight performance cost

#

oh duh

#

just put all that in a variable and refrence that with a ?

#

... nvm sqlite3.OperationalError: table messages has 17 columns but 1 values were supplied

#

Do I just put a bunch of ? marks then have them all afterwards

torn sphinx
#

ok thx

torn sphinx
#

Ok. one other question. For asyncronus operation... should I make the cursor inside the awaited function or just use the same cursor throghout and pass it the cursor

#

Presently I have the cursor created at the start

#

but I assume one cursor can only do one thing at a time

#

yea other examples create cursor inside the function so that is probably correct

proven arrow
#

Cursors should not be used globally.

torn sphinx
#

yea wasn't thinking so

proven arrow
#

Once you are done with it dispose of it.

#

They are lightweight objects anyways so its ok to recreate them

torn sphinx
#

oh. do I need to close them? or just let them go away with the function end

#

or with cursor

proven arrow
#

Well if you use a with block, they would close automatically. Otherwise you can manually call cursor.close().

torn sphinx
#

ok will use with block

#

oh is their any way to escape the ? substitution of doom?

proven arrow
#

Im not sure what you mean

torn sphinx
#

Reading a few other articles and they all use somewhat more complex ways of avoiding SQL injection

#

like passing through sql.Literal()

proven arrow
#

This is the best way i.e. prepared statements

torn sphinx
#

Is their any real difference though?

#

like is

cursor.execute("INSERT INTO messages VALUES (?)", value)
#

the same as

value = sql.Literal(value)
cursor.execute("INSERT INTO messages VALUES (value)")
#

Really worried about injection because i'm not planning on running in a container and it will be open to literely everyone

#

lol

proven arrow
#

Then use prepared statements (with the ?). They are the safest way, because the query is pre compiled and sent to the database first. Your parameters will always be isolated, and can never be injected.

torn sphinx
#

Ah ok thx.

torn sphinx
#

can someone tell me why this aint working

proven arrow
torn sphinx
#

erm

#

so do i convert it to string

proven arrow
#

You can get the first element of it

torn sphinx
#

and how would i do this

#

?

proven arrow
#

if x[0] == "your code":

grave eagle
#

hewo ^w^ I feel dumb but do not know what the hell is the problem here

cur.execute(f"SELECT emoji, role, message_id, channel_id, guild_id FROM reactions WHERE guild_id = '{reaction.guild_id}' and message_id = '{reaction.message_id}' and emoji '{str(reaction.emoji)}'")
sqlite3.OperationalError: near "'![zoroark](https://cdn.discordapp.com/emojis/791270455356686366.webp?size=128 "zoroark")'": syntax error
torn sphinx
proven arrow
#

The method fetchall() returns an list of tuples. Each tuple in that list is a row that the query matched.
x[0] just gets the first column of that row.

torn sphinx
#

hm

#

ok

proven arrow
torn sphinx
#

also @proven arrow i fogot to thank you man

#

thanks for the help

proven arrow
#

@grave eagle And dont use f strings for your queries. Instead you want to use a parameterised query.

grave eagle
grave eagle
proven arrow
#

Well then in that case the api is your user/client

torn sphinx
#

@proven arrow

#

can you help me again

#

you're code worked but when i tried to do it with another key it didnt work

#

id 1 worked

#

but the others no\

#
for x in row:

        if x[0] == auth_token:
            return(f"<p> {json_data} </p>")
        elif (x) != auth_token:
            return "<p> Please enter the correct api-key.</p>"
        else:
            return "A error has occured."
proven arrow
#

What doesnt work?

torn sphinx
#

when i do a different key

proven arrow
#

What is auth_token?

torn sphinx
#

auth_token = request.args['api_key']

proven arrow
#

Then the token doesnt match.

torn sphinx
#

it does

proven arrow
#

What is your goal here? What are you trying to do?

torn sphinx
#

a api_key authentication

#

cause im making a api

#

and i need api to auth, and im getting the auth data from sql

#

db

#

@proven arrow

proven arrow
#

So then check if the value exists in the database using a query, instead of with python.

torn sphinx
#

how

#

and i need to do it in python cause the api is in python

#

sql_data = "SELECT encoded_api_key FROM api_auth"

#

that the query

proven arrow
#

SELECT COUNT(*) FROM api_auth WHERE encoded_api_key = 'the_key'
This will return the count of how many rows matched. If its 0, then no result was found.

#

That way you dont need to loop at all, or do any comparisons in your code, because its done by the database.

torn sphinx
#

error

#
import ipinfo
import json
import mysql.connector
import flask
from flask import request, jsonify

mydb = mysql.connector.connect(
    host="freedb.tech",
    user="",
    passwd="",
    database="freedbtech_9ine_auth"
)

app = flask.Flask(__name__)
app.config["DEBUG"] = True

@app.route('/iplookup/', methods=["GET"])
def home():

    access_token = '1c1fe412af2b81'
    handler = ipinfo.getHandler(access_token)
    ip = request.args['ip']
    auth_token = request.args['api_key']

    mycursor = mydb.cursor()

    sql_data = f"SELECT COUNT(*) FROM api_auth WHERE encoded_api_key = {auth_token}"

    mycursor.execute(sql_data)

    row = mycursor.fetchall()

    details = handler.getDetails(ip)

    ip1 = (details.ip)
    hostname1 = (details.hostname)
    city1 = (details.city)
    org1 = (details.org)
    region1 = (details.region)
    country1 = (details.country)
    postal1 = (details.postal)
    country_name1 = (details.country_name)
    timezone1 = (details.timezone)

    json_data = ("{" + f'"ip": "{ip1}","hostname": "{hostname1}","org": "{org1}", "city": "{city1}", "region": "{region1}", "postal": "{postal1}", "country_name": "{country_name1}", "country": "{country1}", "timezone": "{timezone1}"' + "}")

    for x in row:

        if x[0] == auth_token:
            return(f"<p> {json_data} </p>")
        elif (x) != auth_token:
            return "<p> Please enter the correct api-key.</p>"
        else:
            return "A error has occured."

app.run()
#

thats my code

#

can you please help me

proven arrow
#

Do you understand what the query SELECT COUNT(*) FROM api_auth WHERE encoded_api_key = 'the_key' does?

torn sphinx
#

no

#

i only started import mysql.connector today

proven arrow
torn sphinx
#

oh ok

#

sorry didnt see

#

so how would i do a check on this

#

cause i dont need to get the count

#

i need to get the api key from db

#

nothing else

proven arrow
#

You already have the key, because you got it from the request? Otherwise how would you check in the database with that query if it exists?

torn sphinx
#

yes but i need to do a check to see if the key exists

#

thats why its api key authentication

proven arrow
#

The result of that query tells you if the value exists or not.

torn sphinx
#

but it didnt work

#

and i dont check if the value exists

#

i need to see if the key exists

proven arrow
#

Ive told you quite a few times now on what the query does. Maybe you need to think about this logically and then try to figure out what it is your doing/not doing.

torn sphinx
#

i know im doing

#

but the query you send me doesnt work

#

i need to check for APIKEY not VALUE

umbral lark
#

Hey, I'm new to databases, and I've got a question.
I thought about working with sqlite, but I heard, that MySQL is faster, because it's online.
If I now wanted to host some application online (on a VPS or sth), then the sqlite db would be a file within the application, right? But how would I go about using MySQL for my application?

pure cypress
#

Yes it's generally faster as you scale up the number of concurrent connections

pure cypress
#

You'd pass a connection string containing the host and credentials to a python library that will connect to the db and let you interact with it

torn sphinx
#

@pure cypress can you help me with something please

pure cypress
#

Please don't unsolicitedly ping people for help

torn sphinx
#

sorry

#

but can you help me

#

?

#
import ipinfo
import json
import mysql.connector
import flask
from flask import request, jsonify

mydb = mysql.connector.connect(
    host="",
    user="",
    passwd="",
    database=""
)

mycursor = mydb.cursor()

sql_data = "SELECT encoded_api_key FROM api_auth"

mycursor.execute(sql_data)

row = mycursor.fetchall()

app = flask.Flask(__name__)
app.config["DEBUG"] = True

@app.route('/iplookup/', methods=["GET"])
def home():

    access_token = ''
    handler = ipinfo.getHandler(access_token)
    ip = request.args['ip']
    auth_token = request.args['api_key']

    details = handler.getDetails(ip)

    ip1 = (details.ip)
    hostname1 = (details.hostname)
    city1 = (details.city)
    org1 = (details.org)
    region1 = (details.region)
    country1 = (details.country)
    postal1 = (details.postal)
    country_name1 = (details.country_name)
    timezone1 = (details.timezone)

    json_data = ("{" + f'"ip": "{ip1}","hostname": "{hostname1}","org": "{org1}", "city": "{city1}", "region": "{region1}", "postal": "{postal1}", "country_name": "{country_name1}", "country": "{country1}", "timezone": "{timezone1}"' + "}")

    for x in row:

        if x[0] == auth_token:
            return(f"<p> {json_data} </p>")
        elif (x) != auth_token:
            return "<p> Please enter the correct api-key.</p>"
        else:
            return "A error has occured."

app.run()
#

the aeron key workds

#

but when i do the qorrds key it dont wokr

#

work*

#

can you please help me

#

@pure cypress , i dont know what unsolicitedly means

#

@torn sphinx why you showing token

#

cause its on my local host

#

so it dont really matter for now

#

and there testing ones

#

🀣 @torn sphinx you think im dumb enough to show the actuall data that is going to be used

#

** Can anyone help me ? **

pure cypress
#

Unsolicitedly means that you ping me out of the blue or randomly.

torn sphinx
#

oh ok sorry

#

please can you help me?

pure cypress
#

What's not working?

#

You were too vague

torn sphinx
#

its only checking for the top api key

#

aeron1234

#

but when i try qorrds1234 it dont work

pure cypress
#

What happens with the other key?

torn sphinx
#

return "<p> Please enter the correct api-key.</p>"

#

Working key

#

Not working

#

even tho there both in the db

brazen charm
#
if x[0] == auth_token:
   return(f"<p> {json_data} </p>")
elif (x) != auth_token:```
pure cypress
#

You need to let your loop check all the keys before returning an error

brazen charm
#

they're two very conflicting if statements you got there

pure cypress
#

Right now you return an error if the first key you check is invalid

torn sphinx
#

so how would i do this

#

a while lopp

#

loop?

pure cypress
#

A for loop is fine

torn sphinx
#

it does

#

for x in row:

    if x[0] == auth_token:
        return(f"<p> {json_data} </p>")
    elif (x[0]) != auth_token:
        return "<p> Please enter the correct api-key.</p>"
    else:
        return "A error has occured."
#

__ ** for x in row: ** __

pure cypress
#
for ...:
  if equal:
    return "they match"
# At this point, if the loop has ended it means none were equal
return "invalid"
torn sphinx
#

for auth_token = row

#

?

#

in*

pure cypress
#

It's pseudo code for the kind of loop you'd need to validate the token

torn sphinx
#

equal is not defined

#

im new to python if you couldnt tell

pure cypress
#

Err it's just pseudo code

#

So it's not exactly what you need to write

torn sphinx
#

idk these big words man

pure cypress
#

By "if equal" I just meant you replace that with the actual comparison of api keys

torn sphinx
#

what do i put after for then

pure cypress
#

Sorry I took for granted you'd follow that.

torn sphinx
#

for x in a row

pure cypress
#

Yes you need to loop over the results of your sql query

torn sphinx
#

for x in row:
if auth_token == x[0]:
return "<p> It worked </p>"

return "<p> invalid </p>"
#

should that work

pure cypress
#

Try it

torn sphinx
#

thank you man

#

ily πŸ’‹

#

no homo

real hemlock
#

Is there a way to use to execute a statement like this

SELECT time // 86400 AS day, COUNT(*) FROM table GROUP BY day

Without having to select the day? As in only selecting the COUNT(*) but still creating the day variable to group by

brazen charm
#

isnt that literally just the where clause

#

WHERE day = (time // 86400) or what ever

real hemlock
#

maybe? I didn't know you could do that

#

i'll try now

#

no it is not

#

day is not an column, time is

brazen charm
#

so let me get this straight

#

i take it

#

does it matter if the groups are in numerical order in some way

#

if not then you can just do the math on the time coloumn then order it because it'll naturally group the times together

#

if it does matter

#

use a Self JOIN ig?

pure dirge
#

Hey everyone I Have a vague question

#

I am collecting some info and some of it is very obvious in length and what the answers will be, for example boolean returns or simple strings like 'orange'/'blue' etc.

I have some other data that is pulled from the same page that's a little longer and more free form in length (Descriptions)

So right now I think saving all the first stuff is easily done in a cvs, but not sure giant paragraphs should also go in that lol

spark parrot
#

How can i storage images into a sqlite column? for each product i have?

craggy arrow
proven arrow
torn sphinx
#

firbase
sqlite
mongodb

#

which one is the best !?

steep bloom
#

mongodb @torn sphinx

torn sphinx
#

okey ty

proven arrow
# torn sphinx which one is the best !?

Sqlite and Firebase/MongoDB are two completely different database systems. Sqlite is relational, uses SQL and has a schema, whereas Firebase/mongo do not give you this. There is no best, and each has is good for different use cases.

spark parrot
#

Hello There i have a problem:
for i in range(len(columns)):
c.execute("SELECT * FROM " + table + " WHERE " + columns[i] + " LIKE " + "%" + searched + "%")

#

is returning.. sqlite3.OperationalError: near "%": syntax error

#

how can i solve this?

shell ocean
#

@spark parrot what are you trying to do

spark parrot
#

Hello!

shell ocean
#

hellos

spark parrot
#

Im triying to search for a word in all the columns of a table and then returning all matches

shell ocean
spark parrot
#

the "?"?

shell ocean
#

also, the table name is known, right?

#

yup

spark parrot
shell ocean
#

you should use that in place of searched

#

then

#

it should be in the string directly too

spark parrot
#

so.... searched="%Hello%"

#

?

shell ocean
#

no

#

like

#

SELECT * FROM this_table WHERE this_column LIKE %?%

spark parrot
#

ok... let me try

shell ocean
#

okay

#

in general

#

you should pass a single string

#

not like

#

the result of string concatenation

#

and then the parameters separately

#

sqlite3 does it a certain way

#

that you can Google

#

that I don't remember because I don't use it but it's as a tuple I think

spark parrot
#

ok, im going to do it, give me a moment

#

@shell ocean c.execute("SELECT * FROM " + table + " WHERE " + columns[i] + "LIKE %?%", (searched))

sqlite3.OperationalError: incomplete input

shell ocean
#

(searched,)

spark parrot
#

oh... ok

shell ocean
#

why is table in a variable?

spark parrot
#

because i have multiple tables, so i want to be able from a tkinter optiondrop to choose in which do i wanna search the Searched variable

#

@shell ocean c.execute("SELECT * FROM " + table + " WHERE " + columns[i] + "LIKE %?%", (searched, ))
sqlite3.OperationalError: incomplete input

shell ocean
#

I see...

#

you're missing a space before your LIKE I think

spark parrot
#

Let me see

#

c.execute("SELECT * FROM " + table + " WHERE " + columns[i] + " LIKE %?%", (searched,))
sqlite3.OperationalError: near "%": syntax error @shell ocean

shell ocean
#

it's mega hard to debug this kind of query

#

because

#

it's hard to see what's in table and columns

#

how about

#

you print the full query

spark parrot
#

let me try

shell ocean
#

print("SELECT * FROM " + table + " WHERE " + columns[i] + " LIKE %?%") and print(searched)

spark parrot
#

@shell ocean its not printing it, idk why, let me try another way

#

@shell ocean
SELECT * FROM customers WHERE first_name LIKE
sandra

#

i removed %?% because it was giving me an error

shell ocean
#

maybe sqlite3 uses something other than ?

#

I'm not sure

spark parrot
#

if i do searched="%Sandra%"

#

it works

#

so i will format it and done

#

@shell ocean Thanks for the help

shell ocean
#

what does searched look like

#

seems like a problem there

craggy arrow
#

The query needs to look like this:
query="SELECT * FROM " + table + " WHERE " + columns[i] + " LIKE ?"
And then when your executing this you need to do:
cursor.execute(query, (f"%{searched}%",))

#

The issue here is the query that SQLite ends up getting is:
SELECT * FROM <table> WHERE <columns[i]> LIKE %"searchterm"%
if he does %?%

#

@spark parrot

#

Oh re-reading, it sounds like you already figured that out -_- Ill show myself out

torn sphinx
#

How would I do this:

await cursor.execute("SELECT clean_content FROM messages WHERE author_id=?", int(user.id))
#

It should select the clean_content entries (valid column name) for rows with a certain author_id

#

from the table "messages"

#

It for some reason gives an unsupported type error

#

even though int is correct

radiant elbow
#

you most likely need to give a tuple, not just a single value. ```
await cursor.execute("SELECT clean_content FROM messages WHERE author_id=?", (int(user.id),))

torn sphinx
#

that worked... do not really understand why but ok

#

How can I iterate through?

I tried this:
for text in list(cursor.fetchall()):

#

also without the List and .fetchall

frail abyss
#

Can someone help me? I've tried to convert this string to a python dict for some time now. I've converted all ' to " to see it would help. I've tried the eval() and json.loads() function but both return error. What is wrong with this string, what do i need to format to make it work?

This is the string

{"Item": {"coords": ["45.6 56.3", "45.7 56.4"], "vehicle-name": "vehicle-1", "tilt": [Decimal("89.9"), Decimal("50"), Decimal("29"), Decimal("50")]}, "ResponseMetadata": {"RequestId": "PO0B6QBL3EOA80Q2NQGNTVCBUBVV4KQNSO5AEMVJF66Q9ASUAAJG", "HTTPStatusCode": 200, "HTTPHeaders": {"server": "Server", "date": "Thu, 31 Dec 2020 03:25:27 GMT", "content-type": "application/x-amz-json-1.0", "content-length": "157", "connection": "keep-alive", "x-amzn-requestid": "PO0B6QBL3EOA80Q2NQGNTVCBUBVV4KQNSO5AEMVJF66Q9ASUAAJG", "x-amz-crc32": "1945811615"}, "RetryAttempts": 0}}
torn sphinx
#

did you try string = string.json()?

#

@frail abyss

frail abyss
#

No, i'll try that! Hold on

#

so new_string = string_name.json()

#

?

#

Never used that function before

#

@torn sphinx

torn sphinx
#

yes that should work

#

json.loads(string) should do the same though

#

Are you sure its valid json?

frail abyss
#

I'm not sure, not to familiar with json

#

Didn't work that function either, since the string isn't a json already

torn sphinx
frail abyss
#

Or maybe i called the function wrong

#

Any idea what I need to change?

#

Seems this line is the problem?

"tilt": [Decimal("89.9"), Decimal("50"), Decimal("29"), Decimal("50")]

torn sphinx
#

yea

#

Decimal

frail abyss
#

DynamoDB that added the Decimal before the value?

#

Why are they doing that? hmm...

torn sphinx
#

Decimal is not a valid json thing

#

you can put that in quotes

frail abyss
#

Yeah so "Decimal("89.9")" would work? Probably will maybe see how to remove those Decimal from DynamoDB from the start

torn sphinx
#

Yes should

#

their may be some way to convert that... idk how

frail abyss
#

Hmm... Probably just going to be lazy and store every number in the database as a string I guess

torn sphinx
#

I would just add in regex replace to remove it

#

Any chance you know how to itterate through a sqlite result?

frail abyss
#

never messed around with sqllite, just some t-sql so don't think I would be of great help

torn sphinx
#

ah well worth a shot

frail abyss
#

@torn sphinx Are you good with regex? How would i remove from Decimal("89.9") so only 89.9 is left?

torn sphinx
#

Sorry i'm terrible at regex I'm sure I could figure it out but so could you.

#

your going to have to research that

frail abyss
#

Haha yeah I guess, just regex is a pain in the ass, worth a shot. Thanks anyways

radiant elbow
#

!e ```
s = 'Decimal("89.9")'
s2 = s.strip('Decimal()"')
print(s2)

delicate fieldBOT
#

@radiant elbow :white_check_mark: Your eval job has completed with return code 0.

89.9
radiant elbow
#

str.strip() removes any character from a given list of characters from the beginning or the end of a string.

torn sphinx
#

I assumed that their might be parentheses elsewhere that were needed though

#

or other letters

#

and it was in the middle of the string

torn sphinx
#

How could I model attributes for products?

#

So like when people click a page it shows all products, then they click a button it filters by for example colour red, or another button to filter by size . Like this

river vortex
#

What is the work of 'COUNT' here?? ''''' SELECT COUNT(from_id) AS inbound, old_rank, new_rank, id, url
FROM Pages JOIN Links ON Pages.id = Links.to_id
WHERE html IS NOT NULL AND ERROR IS NULL
GROUP BY id ORDER BY id,inbound ''''''

torn sphinx
#

@river vortex is counting how many values for that column like how many rows

#

But it's not include the null values of that column

river vortex
#

@torn sphinx Does it select duplicates??

torn sphinx
#

I think yeah

river vortex
#

Ohh...Thanks a lot...

vocal moon
#

Im trying to design my database but im having some issues.

For each guild there will be multiple users, new users are added constantly
For each guild there will be multiple products, the guild owner can remove or add more

Each user is able to purchase products, therefor I need some way of giving each user products

#

Im not sure how to do that

#

i thought about arrays but that just seems flimsy

craggy arrow
#

You need to look at many-to-many relationships

#

In database modeling

#

It seems you have 3 tables:

Guilds
Users
Products

And then various relationships between them. Which will likely need to be represented by a many to many relationships:

UsersProducts
GuildsProducts
GuildsUsers

vocal moon
#

would UsersProducts, etc be separate tables?

craggy arrow
#

No

vocal moon
#

oh, there related

#

Guilds
Users
Products

#

so like the data is interlinked?

craggy arrow
#

Right, the "link tables" just have 2 columns, that point to the left and right hand side of the relationship

#

So like UsersProducts would be like:
| user_id | product_id |

#

Where user_id and product_id are foreign keys to the user and product tables respectively

#

You can model the other relationships in the same way.

vocal moon
#

can you give me an example of what my products table may look like

#

with user_id be a list of users who have the product

craggy arrow
#

Maybe something like:
| product_id | name | price | ... other stuff just about product ... |

#

and users might be:
| user_id | name |

#

Are you using SQL Alchemy or just hand writing?

vocal moon
#

postgres and pgadmin

vocal moon
craggy arrow
proven arrow
craggy arrow
#

Yeah it depends, I figured the same product could be found for multiple guilds

#

or users can be in multiple guilds, if they can't then you can have simpler tables

#

User's Products still need to be many-many though

#

So are the requirements:
Guilds can have many users, and many products
Users can only have 1 guild
Products belong to 1 guild
Users can have many products

#

?

vocal moon
#

users can be in multiple guilds but products for this user are guild specific
and yes, each product belongs to only one guild

craggy arrow
#

Alright, so this is how I would model this, (bare with me a second)

vocal moon
#

okie

craggy arrow
#
Guilds
| guild_id | owner_user_id_fk | ... more data columns as needed ... |

Products
| product_id | guild_id_fk | ... more columns as needed ... |

Users
| user_id |  ... more columns as needed ... |


GuildUsers
| guild_id_fk | user_id_fk |

UsersProducts
| user_id_fk | product_id_fk |```
#

So this assumes guilds can have only 1 "owner"

#

When I say "more data columns" I just mean I assume you have some stuff like the guild / user name, etc ...

#

anything ending with _fk means "Foreign key" to one of the "core" tables

vocal moon
#

i still dont understand what UsersProducts or GuildUsers would be

#

because you said it wouldnt be a table right

craggy arrow
#

Oh, sorry if I said that I must have misunderstood, it will be a table

#

GuildUsers makes a link between the users table and the guild table, UsersProducts make a link between users and products

#

Because you said Products are specific to only one guild, the relationship between Guilds and Products is on the products table (meaning 1 guild to many products)

vocal moon
#

ohhhh

#

i understand

#

thank u

#

so

#

much

#

❣️

#

no homo

craggy arrow
#

No problem, this is kind of a classic db modeling problem πŸ˜„ and I like those

fading breach
#

I have this at the top of my code db=pickledb.load("economy.db", False), but how can I set it to True, later in a command

craggy arrow
#

@fading breach hard to help without some code, can you paste what you have?

fading breach
#

its fine, I figured it out

craggy arrow
#

πŸ‘

glass gorge
#

hey

#

im getting a qlalchemy.exc.DataError: (pymysql.err.DataError) (1406, "Data too long for column

#

but the model is long enough to handle the input

#

so idk

#

maybe my orm isnt updating properly?

#

not sure

glass gorge
#

can anyone advise on this?

#

hmmm i checked the db and it looks like it isnt updating it correctly

#

flask migrate

high sparrow
#

I am trying to created a new Dataframe from an existing one, this works for the first colum but the second colum i am trying to create always has "NaN" as its values, there are obviously values in my Original Dataframe at that space but for some reason they are not being read

my first Dataframe:

import pandas as pd
import matplotlib.pyplot as plt
df = pd.readcsv('C:/Users/andi/OneDrive/Desktop/UNI/Angew_SYS1/Projekt/2012_gwr_sprengelerg.csv', sep = ';', encoding='cp1252')
df

This is how i want to create my Second Dataframe:

dataframe = pd.DataFrame(columns=['stimm',"stimm2"])
dataframe["stimm"] = df.loc[df['ptname'] == 'SPΓ–', 'stimmen']
dataframe["stimm2"] = df.loc[df['ptname'] == 'FPΓ–', 'stimmen']
print(dataframe)

My output is this:

stimm stimm2
2        32    NaN
13       46    NaN
24       41    NaN
35       39    NaN
46       48    NaN
...     ...    ...
2939     57    NaN
2950     74    NaN
2961     82    NaN
2972    535    NaN
2983     42    NaN

Does anyone know how i should go about this?

glass gorge
#

let me refine my question

#

flask migrate, is not handling column datatype size changes

#

i read online that it doesnt handle column datatype changes, I assume this means that changing the size is also an issue

craggy arrow
#

i read online that it doesnt handle column datatype changes, I assume this means that changing the size is also an issue

#

You got it

#

And that's actually because alemibic can't do it

#

you need to write a migration script for alembic by hand

#

I assume you used:
flask db revision ? probably with --auto-generate

#

You'll need to go into the script and add the stuff alembic couldn't do

#

Alembic is only able to do like 80% of stuff automatically

glass gorge
#

i see

#

well, I read that i could just do compare_type=True that seems to have solved the issue

glass gorge
craggy arrow
#

Oh really? That's cool

craggy arrow
glass gorge
#

well yeah

#

but you said write a script manually for the migration

#

confused about that portion

craggy arrow
#

so if you don't do --auto-generate then you just get a stub alembic script with the upgrade / downgrade functions left for you to write code for

#

Seems type compare works for your situation, I think there are some situations alembic cannot really handle though, in which case you have to hand write the migration

#

And there are other reasons too, like moving data from an old table to a new table, etc ...

glass gorge
#

new to the orm and migrations in general

#

guess i need to do some more digging on writing migration scripts

craggy arrow
#

Well sounds like you don't have to do it in this case

glass gorge
#

have just been running 3 commands, stamp head, migrate, and upgrade

craggy arrow
#

but I've seen alembic fail to figure out what its supposed to do

glass gorge
#

yeah it seems kinda garbage

craggy arrow
#

Well, I mean it does save you some work? But its not automagic, like we use SQLAlchemy and Alembic at work, and we always double check the scripts that alembic generates

glass gorge
#

it does

#

i guess 80%

#

is better than 0%

#

seems touchy though, sensitive

craggy arrow
#

Yeah that's the point, but it is annoying you have to go back and double check it

#

Well and like it kind of generates shit revision script names out of box

glass gorge
#

yeaaa

#

omg those hashes

craggy arrow
#

Yeah you can fix that

glass gorge
#

"delete the most recent one"

#

ok but which one

#

lmao

glass gorge
#

or how

craggy arrow
#

There's a setting, let me see if I can find it

#

in the alembic ini

glass gorge
#

cool

#

lmk

craggy arrow
#

Im not sure how you specify it with flask-migrate

glass gorge
#

I do have another question after

#

regarding declaring timestamp column in sqlalchemy

craggy arrow
#

BTW, in the alembic section of the ini you can do:

#

file_template = %%(year)d%%(month).2d%%(day).2d_%%(rev)s

glass gorge
craggy arrow
#

so the name will then come out YYYYMMDD_<hash>.py

#

? Im talking about how to make alembic generate sequential filenames for the upgrade scripts

#

so the last one is the last upgrade, if you listed the directory

glass gorge
#

so my ini has a bunch of "headers"

#
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S```
#

handler_console

#

for example

craggy arrow
#

Ooooh

#

it goes in [amelbic]

#

er

#

[alembic]

glass gorge
#
[alembic]
file_template = %%(year)d%%(month).2d%%(day).2d_%%(rev)s```
craggy arrow
#

Yeah

glass gorge
#

thx

#

err regarding the timestamp

#

datatype

craggy arrow
#

Yup?

glass gorge
#

what's the syntax for sqlalchemy?

#

I looked in the docs

#

and it was just TIMESTAMP()

#

but that keeps kicking back an invalid datatype

#
    upload_timestamp = db.Column(db.TimeStamp())
AttributeError: 'SQLAlchemy' object has no attribute 'TimeStamp'
craggy arrow
#

Date/Datetime

glass gorge
#

oh

#

so datetime = timestamp

#

seems weird

craggy arrow
#

Oh

#

theres one specifically for like unix epoch stamp

#

So there's date for a date with no time stamp, datetime for date+timestamp, and then for the epoch date stamp (seconds from like Jan 1, 1970 or something) you use Time IIRC

#

If you use PyCharm or a similarly intelligent IDE the autocomplete can help you out for this kind of thing too.

glass gorge
#

i do use pycharm

#

but i think its datetime

craggy arrow
#

Yeah, well I mean there's timestamp if you want it

#

I'd just keep type_basics open

#

while your working on stuff

glass gorge
#

idk that didnt seem to work

#

it seems to have logged a null response

craggy arrow
#

Whats your model look like?

glass gorge
#

class Phone_Survey(db.Model):
    __tablename__ = "phone_survey"
    __bind_key__ = "user_data"


    survey_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    interviewer_id = db.Column(db.String(20), nullable=True)
    first_name = db.Column(db.String(20))
    last_name = db.Column(db.String(20))
    upload_timestamp = db.Column(db.DateTime())
    time_customer_drop = db.Column(db.DateTime)```
#

this is the shorter version

#

im looking at the upload_timestamp var

#
WARNING in survey_form: Invalid datetime value submitted: Could not match input '' to any of the following formats: YYYY-MM-DD, YYYY-M-DD, YYYY-M-D, YYYY/MM/DD, YYYY/M/DD, YYYY/M/D, YYYY.MM.DD, YYYY.M.DD, YYYY.M.D, YYYYMMDD, YYYY-DDDD, YYYYDDDD, YYYY-MM, YYYY/MM, YYYY.MM, YYYY, W
craggy arrow
#

Your model looks fine, I think where ever your getting the upload_timestamp from is an empty string

glass gorge
#

let me see

craggy arrow
#

Well actually

#

upload_timestamp = db.Column(db.DateTime())
time_customer_drop = db.Column(db.DateTime)

glass gorge
#

yeah

craggy arrow
#

That could be a problem but I don't remember exactly

glass gorge
#

that empty string i think is for the time_customer_drop

#

and i didnt fill that section out

#

the upload_timestamp is something else

#

upload_timestamp | datetime | YES | | CURRENT_TIMESTAMP |

#

hmmm maybe ill set nullable to false

craggy arrow
#

Well you should be able to have a nullable Datetime

#

But

glass gorge
#

not for my usecase though 😐

#

but i see your point

#

that shouldnt cause the error

craggy arrow
#

Yeah I think you have an issue where like

#

The form being submitted back is sending '' for the timestamp

#

and SQLAlchemy is strick and doesn't consider that "None" (which it shouldnt)?

#

Maybe I don't know

glass gorge
#

well theres no field for upload timestamp

#

on the form

#

lol 😦

craggy arrow
#

Well where does it come from, that timestamp? like how are you populating it on the model

#

Im saying that's the problem

#

even if you make that column not nullable you probably will still have issues I think

#

(not a hundred percent sure, debugging fragments of code is not particularly easy :D)

glass gorge
#

it was working before

#

gonna try the null thing

#

then see

#

lol

#

yeah that wasnt it

#

ill dig some more

#

thank you

craggy arrow
#

np

glass gorge
#

not in python

craggy arrow
#

You mean default value for the column?

glass gorge
#

yea

craggy arrow
#

I didn't see you specify that on the model,

#

Think you have to tell SQLAlchemy to do that

glass gorge
#

i had changed the model before

#

so that's prob why

craggy arrow
#

I see I see, you want it to basically be the time the row was inserted, yeah I think you just need to tweak your model

#

Still seems like a weird error

glass gorge
#

just going through my github

#

looking for what i had before

stuck raptor
#

Can someone help me use a SQL data base to store stuff for a discord bot?

glass gorge
#

@stuck raptor i suggest youtube tutorials

stuck raptor
glass gorge
#

I watched a corey schafer video

#

on building a flask app, and working with mysql db

#

there are also some on digital ocean

#

that I followed

#

I don't know how discord bots work

#

but you'd need to basically link the bot to the db

pure dirge
#

Big pizza

#

Hello everyone.

glass gorge
#

big pizza deez

pure dirge
#

Anyone know how to manipulate a csv XD

glass gorge
#

sure

#

use hammer

pure dirge
#

Hammer?

glass gorge
#

yeah use a hammer

#

im jk

#

what do you need help with

stuck raptor
glass gorge
#

nope :/

pure dirge
#

organising the csv basically

glass gorge
#

idk

#

but i think datascience sounds more appropriate for this

#

are you using pandas?

#

is this in a db

#

youd prob have to use the selector method dataframe[]

#

then do your manipulations

snow knot
#

hello?

#

does anyone know how to make a database for saving a game

#

like a multiplaye rgame

stuck raptor
#

Can someone help me with making a table in MySQL?

pure dirge
rugged ginkgo
#

Would this be the place to ask a library specific question about asyncpg?

craggy arrow
#

Probably not here unless their GH Readme pointed you here

torn sphinx
craggy arrow
#

Well, it is, that doesn't mean anyone here has any experience with it.

#

They probably have their own discord / IRC channel / mailing list / <obligatory comms channel>

rugged ginkgo
#

Thanks πŸ™‚

torn sphinx
#

Anyone pymongo dev here?

pale canopy
#

I'm using PyMongo to make a DB using MongoClient and I keep getting connection refused error py pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [WinError 10061] No connection could be made because the target machine actively refused it, Timeout: 30s, Topology Description: topology_type: Single, servers: [<ServerDescription ('localhost', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('localhost:27017: [WinError 10061] No connection could be made because the target machine actively refused it')>]>

#

I don't get how it doesn't work on localhost?

vivid delta
#

I am getting pgconfig error while executing my postgres script on a server, I searched github and it says to bump pgproto, can anyone give me an idea about it?

zinc mist
#

Hey everyone a newbie to python scripting is here, I want to share my Chrome extractor version 😊, and I want you all to tell me your comments and advices to learn more about this stuff.
This Python script will extract all saved passwords from your google chrome database and save it in a hidden file chrome.txt : https://github.com/Reda-BELHAJ/Chrome-Extractor

craggy arrow
zinc mist
#

@craggy arrow this version is way cooler ngl

craggy arrow
#

Yeah its nice, it covers Nix and Mac. I haven't been on windows for ages now.

scarlet dagger
#

i'm new to sql server. I want to secure my website from sql injection. What method is used to secure website. can anyone help please?

craggy arrow
#

Use prepared statements is the main advice

#

Don't do things like:
cursor.execute(f"INSERT INTO table (column_name) VALUES ({raw_user_input})")
Do instead
cursor.execute("INSERT INTO table (column_name) VALUES (?)", (raw_user_input,))

#

If you're using SQL Alchemy, and don't hand write any queries, you're probably already protected @scarlet dagger

craggy arrow
#

It's an object relational mapper for Python that turns class definitions in your python code into Database tables / entities:
https://github.com/sqlalchemy

#

It's the de-facto ORM most people use in Python.

scarlet dagger
#

ok Thanks @craggy arrow

craggy arrow
scarlet dagger
#

Do you have an any idea how to secure in php?

craggy arrow
#

Its the same strategy in every language, use prepared statements, don't put user input directly into the Query strings

scarlet dagger
#

I use Store Procedure

#

but nothing works for me

craggy arrow
#

I'm not a fan of sprocs and don't really use them but I think the same thing applies for that.

#

What DB Backend you using? (MySQL, PSQL, MS ... ? )

scarlet dagger
craggy arrow
#

Its still the same, all database backends implement prepared statement functionality.

scarlet dagger
#

ok i try

craggy arrow
#

Also if you want help with PHP, you might try a community focused on PHP instead of Python πŸ˜„ But since this is a general database question I guess its fine.

eternal raptor
#
async def create_db_pool():
    client.conn = await asyncpg.create_pool(user="bot", password="Sebi2006", database="ninjamnrdb", host="127.0.0.1")```
Password is correct, asyncpg is imported.
craggy arrow
#

@eternal raptor would help if you posted some context, but considering there's an authorization error, you should probably check that user+pass combo with something like pgadmin

eternal raptor
#

pgadmin works

#

dbeaver too

craggy arrow
#

ninjamnrdb
^ When this db is specified?

eternal raptor
#

database="ninjamnrdb"

#
NinjaaaSKDziΕ› o 14:37
async def create_db_pool():
    client.conn = await asyncpg.create_pool(user="bot", password="Sebi2006", database="ninjamnrdb", host="127.0.0.1")
craggy arrow
#

Oh it says invalid password, nvm

eternal raptor
#

wait

#

please

#

I connected with database in pgadmin correctly

craggy arrow
#

Port 5432 ?

eternal raptor
#

127.0.0.1:61462

craggy arrow
#

No I mean, is the port the db running on the standard one

#

5432, and are you sure you're not running 2 DB instances?

#

I mean unless there's a serious bug in asyncpg (I doubt it) the error is straight forward: either you're not connecting to the database server you think you are, or the password is wrong.

eternal raptor
#

eee what? wait, Could you tell me how to check port?

craggy arrow
#

Can you show me the settings for the database in PGAdmin?

eternal raptor
#

yes, i can.

craggy arrow
#

If you want to DM them to me that's fine

eternal raptor
#

yup

craggy arrow
#

(got him covered :D)

fading breach
#

@maiden light can you help me with mongodb?

maiden light
#

@fading breach Alright

fading breach
#

I created a cluster

#

whats next

#

I found a YT tutorial

#

I will follow that

maiden light
#

Create a database user with a password that you remember, it should have all access

fading breach
#

ok

#

done

maiden light
#

Well let me login I can't remember much

#

I apparently can't login, well allow all ip addresses or depends on you, that can access your db.

#

Add 0.0.0.0 as an ip to allow everyone

#

Create a database

#

Add a collection

#

Click on CONNECT on your cluster and then application, then set driver as Python 3.4+ and get the connection url, in that url change pass to the database user password you created, and done.

#

With that url you can add records, install Motor

fading breach
#

@maiden light I have completed setup, how can I dump stuff into thew database

tall olive
#

Looking for feedback and pointers to similar work so I can learn about prior art in this area

elfin wigeon
#

Hello guys. I have a question. Is it possible to add a path and work with two work directories like in matlab?

torn sphinx
#

is it possible to connect your database (from mongodb) to a website ?

#

Just wanted to say thanks for this

jovial notch
#

@radiant elbow lmk if u could help, you helped me last time πŸ˜›

torn sphinx
#

oh

#

i can help you

radiant elbow
#

that's not got anything to do with databases - the error there is that data is a string, and you're using 'id' as an index into it.

torn sphinx
#

data is returning a string not list

#

array **

jovial notch
#

@radiant elbow @torn sphinx why is that tho like I have more codes that are like these? for example

radiant elbow
#

data in that one is the return from fetchrow - it's the return from execute in the other.

jovial notch
#

@radiant elbow so what do I need to fix?

radiant elbow
#

you probably are missing a call to some fetch* function

jovial notch
#

what is the difference between fetch, fetchrow and execute?

radiant elbow
#

what library are you using?

jovial notch
#

asyncpg @radiant elbow

radiant elbow
#

fetch runs a statement and returns the result as a list of records. fetchrow returns a single record, the first row of the result set.

jovial notch
#

ok 1 more question, difference between integer and bigint? @radiant elbow

radiant elbow
#

integer has a maximum value it can hold, bigint is unlimited

jovial notch
#

so like for things like 1 to 10

#

i need integer?

#

why cant it work with bigint?

radiant elbow
#

it would work with bigint - just slower.

#

bigint can hold any integer, integer can hold only integers within a certain range.

pale canopy
#

I'm using PyMongo to make a DB using MongoClient and I keep getting connection refused error py pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [WinError 10061] No connection could be made because the target machine actively refused it, Timeout: 30s, Topology Description: topology_type: Single, servers: [<ServerDescription ('localhost', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('localhost:27017: [WinError 10061] No connection could be made because the target machine actively refused it')>]>

radiant elbow
#

do you have the same problem if you remove the ( and ) from inside query1? The column list for a select shouldn't be surrounded in ()

jovial notch
#

damn u know a lot appreciated also whats fetchval?

shell ocean
maiden light
#

To find it

find = await db["collection name"].find_one({"id": 1234})
find["balance"] # will give balance

Also

find = await db["collection name"].find_one({"balance": 0}) # if more than 1 people have 0 balance, it will give randomly
find["id"] etc.
#

find instead of find_one will give all people having 0 balance, there is update_one, update_many, insert_many, you can look at docs.

#

To update

await db["collection name"].update_one({"id": 1234}, {"$inc": {"balance": 500}})
# Here $inc means increase, it will add 500, if you use $set it would set the balance to 500 instead of adding.
torn sphinx
radiant elbow
#

oof, so it does. My mistake for assuming.

#

It's weird that they call that bigint instead of int64, at least to my sensibilities...

torn sphinx
#

Is it also unlimited in python or is different?

radiant elbow
#

Python's int type is unlimited, as are Java and C#'s BigInteger

#

I find it surprising that something would be called bigint and not be unlimited - everything I've ever seen before that's called a big integer is unlimited.

torn sphinx
#

oh i thought everywhere it was limited to 64 bit

#

i didnt know this til

radiant elbow
#

I mean, the postgres bigint type is limited to 64 bits, but big integers in other languages aren't

torn sphinx
#

Thats nice

radiant elbow
#

!e ```py
print(2**100)

delicate fieldBOT
#

@radiant elbow :white_check_mark: Your eval job has completed with return code 0.

1267650600228229401496703205376
radiant elbow
#

^ more than 2**64 πŸ™‚

torn sphinx
#

So does this have anything do with IEE64
or is that for something else

radiant elbow
#

nope, completely unrelated to that.

torn sphinx
#

Oh yeah i remember that is for floating points right?

radiant elbow
#

right. and it still has a limit

torn sphinx
#

Oh so that has a limit. Ok now i see. I thought it was other way round.

radiant elbow
#

IEEE-754 double precision floats (which take up 64 bits) can't represent integers above 2**53 precisely

#

(or below -2**53)

torn sphinx
#

Understand, thanks. I thought floats were more precise befor

radiant elbow
#

they have a wider range, but limited precision.

torn sphinx
#

Thanks

radiant elbow
#

!e ```py
print(2.053)
print(2.0
53+1)
print(2.0**53+2)

delicate fieldBOT
#

@radiant elbow :white_check_mark: Your eval job has completed with return code 0.

001 | 9007199254740992.0
002 | 9007199254740992.0
003 | 9007199254740994.0
radiant elbow
#

^ note that line 2 isn't correct, it skipped over ...993.0 because that can't be exactly represented in an IEEE 754 64-bit float.

torn sphinx
#

I see

#

So is this edge case ever affected in real life?

#

Like you cant do some things because of this?

#

Or there is some other way around it

radiant elbow
#

that's a very large number - it's not one that typically comes up when you're dealing with integers, because you rarely have to count 9 quadrillion of something - but it does come up in various types of math, and needs to be accounted for.

frail abyss
#

Don't know where to put this question but anyone good with regex? I what to indentify the word Decimal("98.8"), the number can vary and have different length then just 00.0

I can indentify the last part ") but what to I write to tell to match everything before ") until space?

mild vector
#

Hey, do I lose my databases if I uninstall and then re-install postgresql on Ubuntu 20.04 ?

astral gorge
#
    Is the server running locally and accepting
    connections on Unix domain socket "/run/postgresql/.s.PGSQL.5432"?```
psql seems to have broke after the system update, any tips?
#

systemctl postgresql also doesn't work

mild vector
#

Same problem

#

I tried everything but it didn't work

stark violet
#

I'm very new to databases in python, and I want to learn more about them. Can you guys recommend me a good database that I should start?

stark violet
fading breach
#

mysql is fine

#

postgres

stark violet
#

because I'm familiar with mysql but haven't used it in python

stark violet
fading breach
#

no

#

postgres is a differen database

maiden light
fading breach
#

ok

#

@maiden light can you help me make the switch from pickledb to mongo

#

like step by step

#

for each command

#

do you have some time?

maiden light
#

You know the basics? I mean, insert update delete ?

fading breach
#

ok

maiden light
#

Idk pickledb

fading breach
#

its like json

#

@maiden light <password> should be replaced, right/

maiden light
#

Yes

#

You don't need <> around it

fading breach
#

ok

maiden light
#

Did you make a database, and a collection?

fading breach
#

yes

#

I put the link in

#

so record is the format I want my database to be in

fading breach
#
record = {"id": message.author.id, "balance": current_balance, }
await db["collection name"].insert_one(record)
#

this correct?

maiden light
#

If it is inserting it should be 0?

#

But yeah it's correct

#

Wait you don't need the , after current_balance

fading breach
#
@commands.command()
 async def setup(self, ctx):
    for member in ctx.guild.members:
      record = {"id": (str(member.id)), "job": False}
      await db["Scope Economy"].insert_one(record)
#

is this correct?

#

if it is, I've got the hang of it, thanks

maiden light
#

Well, it isn't :/, you don't have balance or bank, I don't know how you do it, but that False is a SyntaxError.

fading breach
#

im trying to set all the ID's to false

#

or None

maiden light
#

Have something like "status": False

fading breach
#

ok

maiden light
#

Or None

fading breach
#

how about now

#

(I edited the message)

maiden light
#

Yep it's fine

#

But you shouldn't make ids str just saying

fading breach
#

ok

#

how do I find the job of ctx.message.author

maiden light
#

You don't need the ( before str,
record = {"id": str(member.id), ..

fading breach
#

ok

maiden light
#

Wait it's the same message LOL

fiery scaffold
#

Postgress or MySQL...
Which one should I use...?

fading breach
#

is this correct ```py
find = await db["Scope Economy"].find_one({"id": ctx.message.author})
find["id"]

fiery scaffold
fading breach
#

hmm

#

maybe MySQL

#

better for web development

fiery scaffold
#

hmmm...

fading breach
#

im not an expert or anything

fading breach
fiery scaffold
#

well Then I'll see which one of them have better

#

learning resources

#

and community support

fading breach
#

I just see more people use mysql for web

fiery scaffold
#

yaa

#

but isn't postgress getting more and more attention

fading breach
#

yeah

fiery scaffold
#

lately

#

guess ill just toss a coin thenπŸ™ƒ

strong granite
#

Hey guys, looking forward to contibuting to this discord channel as I become more familar with python. I have a simple .JSON parsing question in help room chlorine if anybody could give me some input πŸ™‚

fading breach
#

im getting this error @maiden light InvalidDocument: cannot encode object:

astral gorge
craggy arrow
torn sphinx
#

hello

fading breach
#

Hi, I have this error bson.errors.InvalidDocument: cannot encode object:

#

code: ```py
find = await db["Scope Collection"].find_one({"id": message.author})
get = find["level"]

burnt turret
#

mongodb (or any db that i know for that matter) won't support storing arbitrary python objects like that

placid igloo
#

https://pastebin.com/t9KNptAk What am I doing wrong here? Running any function gives me "Error: Commands out of sync; you can't run this command now"

fading breach
#

oh

#

oops

#

silly me

#
get = find["level"]
TypeError: 'NoneType' object is not subscriptable
#

@maiden light

craggy arrow
#

LOL I like how someone will πŸ‘Ž an opinion but then not bother responding to the person who asked.

burnt turret
#

as in you're query probably had zero matches

fading breach
#

oh

burnt turret
#

assuming you did something like find = await collection.find...

fading breach
#

yeah, it equals nothing

#

thats the problem

burnt turret
#

yeah, so make a case that handles that

#

the case where there's no data matching

fading breach
#

@burnt turret should I make an if statement?