#databases

1 messages Β· Page 122 of 1

torn sphinx
#
File not found [mongodbclient.0]
Neither environment variable nor client file exist
Abort```
#

I have no idea why it isn't connecting

vale sphinx
#

I have no previous knowledge of bigquery, and I am trying to follow the instructions on this article https://github.com/PolyAI-LDN/conversational-datasets/tree/master/reddit to get a big dataset to train a chatbot. I have followed the instruction up until ```
Ensure you have a BigQuery dataset to write the table to:

DATASET="data"
bq mk --dataset ${DATASET?}``` but I do not understand how to enter the DATASET="data" command. Can anyone help?

balmy flame
#

Can anyone help me with this error The INSERT statement conflicted with the FOREIGN KEY constraint "FK__DimOrders__DateK__3D5E1FD2". The conflict occurred in database "TeaNMe", table "dbo.DimDate", column 'DateID'.

torn sphinx
#

    query9 = """CREATE TABLE IF NOT EXISTS autorole (
                guild_id bigint,
                all bigint[],
                human bigint[],
                bot bigint[],
                PRIMARY KEY (guild_id)
                )"""
    await bot.db.execute(query9)
    print(Fore.CYAN + f"[TABLE] prefix created")
#
  File "C:\Users\91782\Desktop\PostgreSQL\bot.py", line 97, in <module>
    loop.run_until_complete(start_db(bot))
  File "C:\Users\91782\AppData\Local\Programs\Python\Python38-32\lib\asyncio\base_events.py", line 616, in run_until_complete
    return future.result()
  File "C:\Users\91782\Desktop\PostgreSQL\bot.py", line 66, in start_db
    await create_tables(bot)
  File "C:\Users\91782\Desktop\PostgreSQL\cogs\utils\cache.py", line 167, in create_tables
    await bot.db.execute(query9)
  File "C:\Users\91782\AppData\Local\Programs\Python\Python38-32\lib\site-packages\asyncpg\pool.py", line 518, in execute
    return await con.execute(query, *args, timeout=timeout)
  File "C:\Users\91782\AppData\Local\Programs\Python\Python38-32\lib\site-packages\asyncpg\connection.py", line 272, in execute
    return await self._protocol.query(query, timeout)
  File "asyncpg\protocol\protocol.pyx", line 316, in query
asyncpg.exceptions.PostgresSyntaxError: syntax error at or near "all"```
proven arrow
#

@torn sphinx all is a postgres operator so it thinks your trying to use that

#

You can change column name to something else or escape it by putting double quotes around it

torn sphinx
#

oh

proven arrow
#

It's the same. Directly using execute will get aquire the connection for you.

torn sphinx
#

so

    query9 = """CREATE TABLE IF NOT EXISTS autorole (
                guild_id bigint,
                "all" bigint[],
                human bigint[],
                bot bigint[],
                PRIMARY KEY (guild_id)
                )"""
    await bot.db.execute(query9)
    print(Fore.CYAN + f"[TABLE] prefix created")
proven arrow
#

I didn't say all the columns, I just said one

torn sphinx
#

alr

torn sphinx
#

Here is a mini project I worked on today to learn data mining. Feel free to add/change something. https://github.com/murathany7/scraper

torn sphinx
#
import pymongo
from pymongo import MongoClient
import os

mongodbclient_token = os.getenv("My mongo connection would be here")

if mongodbclient_token is None:
    try:
        with open('./mongodbclient.0', 'r', encoding='utf-8') as client_url:
            print("Using MongoDB cluster url provided in file")
            cluster = MongoClient(client_url.read())
    except FileNotFoundError:
        print("File not found [mongodbclient.0]")
        print("Neither environment variable nor client file exist")
        print("Abort")
        exit()
else:
    print("Using MongoDB cluster url provided in environment variable..")
    cluster = MongoClient(mongodbclient_token)```
#
File not found [mongodbclient.0]
Neither environment variable nor client file exist
Abort```
cloud pebble
#

Hey guys, What do you think is the best way to connect the a flask app with mysql?
should I use Flask-SqlAlcehmy? or Should I go for Flask-MySqlDB?
In my case the database is already created in Mysql and tables are already connected with each other using foreign key.
Also I got this suggestion that I should use phpmyadmin? I have no idea what's that and leads on this?

cloud pebble
#

I tried connecting MySql to the flask app.
my port number is 3307, I checked it.
here's the Python code:-

from flask import Flask, request, render_template, url_for, redirect
from flask_mysqldb import MySQL
import yaml


app = Flask(__name__)
db=yaml.load(open('db.yaml'))
app.config['MYSQL_HOST']=db['mysql_host']
app.config['MYSQL_USER']=db['mysql_user']
app.config['MYSQL_PASSWORD']=db['mysql_password']
app.config['MYSQL_DB']=db['mysql_db']
app.config['MYSQL_PORT']=int(db['port'])



mysql=MySQL(app)



@app.route('/',methods=["POST","GET"])
def login():
    if request.method =="POST":
        coachDetails=request.form
        name=coachDetails['username1']
        passw=coachDetails['password1']
        conn=mysql.connection()
        cur=conn.cursor()
        cur.execute("INSERT INTO CoachData(cname,cpass) values (%s, %s)",(name,passw))
        mysql.connection.commit()
        conn.close()
        return 'success'
    else:
        return render_template('reg.html')

@app.route('/show')
def user():
    return render_template('show.html')




if __name__=='__main__':
    app.run(debug=True)

here's the Db.yaml code:-

mysql_host: 'localhost'
mysql_user: 'root'
mysql_password: 'yash'
mysql_db: 'loginEx'
port: '3307'

Here's the stack trace:- https://dpaste.org/uNfD

feral thorn
#

how can i dump my whole database on postgres? OS - Ubantu

torn sphinx
feral thorn
#

did that but i don't know where it dumped file

#

i tried searching but couldn't find

#

found that..thanks

lost spear
#

Anyone with experience with SQLAlchemy/postgres that canand wants to help me understand some things? DM me. Cheers.

torn sphinx
#

Hi, does any awesome person know how to replace the ****** in \r\n "geography": ******, with the value 'US'
(from the country variable)????

country = 'US'

payload = "{\r\n    \"groupBy\": \"BgtOcc\",\r\n    \"timePeriod\": {\r\n        " \
        "\"from\": \"2010-01-01T00:00:00\",\r\n        \"to\": " \
        "\"2020-01-01T00:00:00\"\r\n    },\r\n    \"queryString\": \"([nationwide]: " \
        "\\\" nationwide  \\\") AND ([BgtOccFamily]: \\\"Hospitality, Food, " \
        "and Tourism\\\")\",\r\n    \"geography\": ******,\r\n    " \
        "\"includeTotalClassifiedPostings\": true,\r\n    " \
        "\"includeTotalUnclassifiedPostings\": true,\r\n    \"offset\": 0,\r\n    " \
        "\"limit\": 1000\r\n}"
pearl laurel
#

I don't get why mysql does not update the bank amount in the withdraw function, but it works in the deposit function.

code:

    def deposit(self, id, amount):
        cash = int(self.get_cash(id))
        bank = int(self.get_bank(id))

        newCash = cash - amount
        newBank = bank + amount

        updateCash = f"UPDATE user_economy SET user_cash={newCash} WHERE user_id={id}"
        updateBank = f"UPDATE user_economy SET user_bank={newBank} WHERE user_id={id}"

        self.mycursor.execute(updateCash, updateBank)
        self.mydb.commit()

    def withdraw(self, id, amount):
        cash = int(self.get_cash(id))
        bank = int(self.get_bank(id))

        newCash = cash + amount
        newBank = bank - amount
        print(newBank)

        updateCash = f"UPDATE user_economy SET user_cash={newCash} WHERE user_id={id}"
        updateBank = f"UPDATE user_economy SET user_bank={newBank} WHERE user_id={id}"

        self.mycursor.execute(updateCash, updateBank)
        self.mydb.commit()
proven arrow
#

@pearl laurel execute can only execute one query, your passing 2. And you shouldn't be using the cursor like that, instead create it when you need, and dispose of it when done.

pearl laurel
#

how do you dispose a cursor? Define it for each function?

rare belfry
#

can anyone here help me in making a query using django orm ?

#

I have a model with a boolean field and I want to generate a query set with True value at top and False value at bottom

proven arrow
pearl laurel
#

and lastly how to i execute more than 1 query?

proven arrow
#

just use two seperate execute calls since your only making 2 queries.

#

@rare belfry You would need to order by that boolean column. You can have it order by DESC, to give true at top

pearl laurel
proven arrow
#

Your only making 2 queries, why a script?

pearl laurel
#

looks cleaner idk

proven arrow
#

No it does not, and you then have more issues such as passing those values to the script, with a different connection. So leave it as it is, and as last note, dont use f strings for your queries.

alpine dock
#

cursor.execute(f"SELECT user_id FROM levels WHERE guild_id = '{message.guild.id}' and user_id = '{message.author.id}'")
sqlite3.OperationalError: no such table: levels

#

Why is not recognizing the table?

#

nevermynd, fixed

torn sphinx
#

Hey

torn sphinx
#

can any1 help me with a basic sort from database

plush sierra
#

@cloud pebble the problem is still in "conn=mysql.connection()" i don't know how to solve this, you have try maybe on interactive shell, how to connect to the db

vestal kiln
#

anyone know a good api for us stock exchange data feed?

polar badge
#

@vestal kiln so long as your not doing a ton of calls https://polygon.io/ works great on their free plan. But gets expensive after that

Polygon.io

Free stock data APIs. Real time and historical data, unlimited usage, tick level and aggregate granularity, in standardized JSON and CSV formats. Plus currencies data, including forex, crypto, and more.

#

@alpine dock You shouldn't allow people to insert directly into your queries. you should do this first.

cursor.execute(query, (message.guild.id, message.author.id))```
Just note if you only are passing 1 value, you need it to me like `(query, (myValue,))` note the extra comma after myValue.
#

Otherwise someone could do an sql injection attack on you. Not likely, but best practice.

alpine dock
#

i fixed it

#

but thanks anything

polar badge
#

I am trying to use WHERE xyz LIKE but I need to check only the last character. such as xyz[:-1] and that it is equal to 1, the database i have has a bunch of values like something.1, something.2 something.3 and only the .1 do i care about. What's the best way to go about it? I am not figuring it out. figured it out didn't know i could use right(xyz,1)...

vestal kiln
#

Ty

polar badge
#

np

grim pier
#

Anyone any ideas? πŸ˜„

grim pier
#

should i just str replace to remove them?
Or is there an actual way to select it properly without them?

#

Monitor is going out the window soon... LOL

mellow scroll
#

Hey so....

I'm planning on making some software for people to use, and I'm going to need a database, how can I insert data into this database safely, without allowing my users to be able to manipulate, import, edit and read the contents of the database?

#

this program will be publicly available.

#

Please ping me if you respond so i see the message πŸ™‚

radiant elbow
#

no, neither of those are right. You want:

        if row is None:
            query2 = """INSERT INTO antispamnewgen (choice) values ('on')"""
            await bot.db.execute(query2)
        else:
            query3 = """UPDATE antispamnewgen SET choice = 'on'"""
            await bot.db.execute(query3)
#

missing quotes in the "update", and the "insert" wasn't valid at all.

jovial notch
#

appreciated

sly frigate
#

File "C:/Users/Rico/Desktop/Genshin TCG/bot/mongotcg.py", line 4, in <module>
cluster = MongoClient("mongodb+srv://Mash:xxxxxxx@bots-genshin.l2ufp.mongodb.net/genshin?retryWrites=true&w=majority")

#

can iask what error is this?

#

i already updated my mongoDB

#

installed pip

#

when i run it

#

still same error

#

helpppppp

#

anyone here?

pale jay
#

I am trying to make a login system and I want to store the register into a data base can anyone tell me how I can do that?

#

and which database would be good

proven arrow
#

You need to be more specific. What exactly do you need help with? Structuring the schema? Picking if you need SQL Vs NoSQL? Writing the queries? Also more detail on how this system will be used, where and by whom/how many people.

pale jay
#

I am making login system using tkinter and I am making a register function so when they enter the username field and the password field I want it to store to a database

#

should I use mysql connector and get the value entered and then create a table?

proven arrow
#

So you already picked the database you want or you still need to pick one?

pale jay
#

I need to pick one

#

I need SQL

proven arrow
#

So why are you saying MySQL connector already?
Anyways, In terms of picking database you have two options, something like sqlite which is a file based database and the data can be accessed from wherever the file is kept. Or you can have a server based database like MySQL, or Postgres which will allow you to access data remotely over a server/network as well.

pale jay
#

hmm okay

#

I said mysql connector bcuz I only know how to connect mysql with python

proven arrow
#

Sqlite only allows a single writer at a time, as well which you might want to keep in mind.

pale jay
#

oh okay

#

thx

proven arrow
#

And for your schema you would want to have a users table where you store at least the (id, name, email, password, timestamps), and depending on your application functionality you may also want to store extra values like (email_verified, remember_token)

torn sphinx
#

Hello, i was trying to code a "Username Taken" Code

#

NameList = []
name = input("Enter a name : ")
NameList.append(name)
print(NameList)

#

I know this will work

#

but how do i create a database, where the NameList will remember forever that theres a name called amcrq and it can't be used again

#

brb

proven arrow
#

@torn sphinx You can have a UNIQUE constraint on the username column, which would never allow the same value to be inserted into that column more than once.

torn sphinx
#

Back

#

How do i create those constriants

#

@proven arrow In Repl.It, theres a button called databases

#

do i click on that

proven arrow
#

πŸ€·β€β™‚οΈ I never use repl

torn sphinx
#

Import
the database
from replit import db

Insert β†’
Set
a key to a value
db["
key
"] = "
value
"

Insert β†’
Get
a key's value
value = db["
key
"]

Insert β†’
Delete
a key
del db["
key
"]

Insert β†’
List
all keys
keys = db.keys()

Insert β†’
List
keys with a prefix
matches = db.prefix("
prefix
")

Insert β†’

#

Whats this

#

i get this words for database section

#

oh ok

proven arrow
#

Looks like a key value store, maybe that is what they have?

torn sphinx
#

key value

#

my beginners course never included this

#

but i just want to work on something

proven arrow
#

Well what are you trying to store?

torn sphinx
#

So

#

As i mentioned way above

#

I am working on a Username Taken project

#

If i enter the name

#

amcrq

#

amcrq cannot be a name entered

#

This is my Output
Enter a name : amcrq
['amcrq'

#

Forgot the missing bracket

#

so since i ahve entered amcrq

#

it can no longer be used as a name

#

so if i press enter again after typnig amcrq

#

it will print

#

username taken

proven arrow
#

So basically there are two types of databases. SQL and NoSQL. The one you showed from repl is NoSQL, its just like a python dictionary, or a Map in other languages.
Although you can achieve what you want with both, it might be easier for you to implement it in SQL, as it is more simpler I feel for what you are trying to do.
There are different SQL databases. The easiest/simplest is SQLite which comes built into python, and you can have a UNIQUE constraint on the username so it doesn't allow multiple same entries.
But if you want to use the repl database, then you can make the key the username. Although you will have to check their documentation on how it works exactly, because its their own implementation of it.

torn sphinx
#

Ok

#

Sorry i didn't reply

#

I was focused on developing something else in this project

tawny ingot
#

I am trying to select something in my SQlite3 DB

deck = "test"
db = sqlite3.connect("DECKS.db")
cursor = db.cursor()
cursor.execute(f'SELECT NAME FROM DECKS WHERE USERID = {ctx.author.id} AND NAME = {deck}')
result = cursor.fetchone()
print(result[0])```
https://cdn.discordapp.com/attachments/587375768556797982/784724509063249930/unknown.png
and this is the error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OperationalError: no such column: test
though the column exists
#

can someone help me

#

why is this happening

molten sleet
#

:+1:

tawny ingot
shy condor
#

Hey, need some help wiht json

so i created a json file with a dict in it and i have a function that dumps some more dict keys and stuff and this all works. but if i call the function another time and add stuff it overwrites the old stuff

#

how can i make it so it more likeley appends the new stuff?

proven arrow
#

Use this instead, which is also a safer way of making the query.

cursor.execute('SELECT NAME FROM DECKS WHERE USERID = ? AND NAME = ?', (ctx.author.id, deck))
tawny ingot
#

yeah thanks for your help

pale jay
#
CREATE TABLE info(
userid INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR INDEX UNIQUE NOT NULL,
password VARCHAR NOT NULL
);
```What is wrong in this?
#
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INDEX UNIQUE,
password VARCHAR
)' at line 3
proven arrow
#

Put the index at the end of the statement, and also give varchar a value. For ex,

CREATE TABLE info(
  userid INT AUTO_INCREMENT,
  username VARCHAR(255) UNIQUE NOT NULL,
  password VARCHAR(255) NOT NULL,
  PRIMARY KEY (userid),
  INDEX (username) 
);
``` @pale jay
pale jay
#

I will try that

proven arrow
#

Actually wait no

#

I missed something

pale jay
#

but no diff

proven arrow
#

See updated

pale jay
#

the size hmm

#

ok

pale jay
#

worked

mellow scroll
#

Hey so....

I'm planning on making some software for people to use, and I'm going to need a database, how can I insert data into this database safely, without allowing my users to be able to manipulate, import, edit and read the contents of the database?
If someone replies, please @ me so i can see the message πŸ™‚

proven arrow
#

@mellow scroll Well you should not let the users interact directly with the database. That's your applications job to do this. Your app should take the users input, process it and then pass it on to the database.
As some general rules:

  • Never trust the user (validate all input)
  • Never directly insert user input into the database
  • Don't use dynamic queries. Use prepared statements/parameterised queries.
  • Enforce database user privileges - only grant what they need to function, and not more. This is basically what is known as, principle of least privilege.
torn sphinx
#

Hey people, i have a question about design. I have a users table, roles table, and users_role table. This is for my site, where user can have many role so i have many to many relation connection by the users_role table.

#

So my question is, is this bad because if user can have many roles then the entries will get many inside the users_role table. For example, 5000 users with 3 roles each is 15000 entries. Is this bad?

proven arrow
#

@torn sphinx Why would it be bad?

#

Databases are made to store many rows. They were designed for this, and its their job to do this. There is nothing wrong with such an approach as long as you have the proper indexes.

torn sphinx
#

ohh

#

yeah you right, make sense

#

thanks

proven arrow
#

Your application credentials are generally kept in some sort of configuration or environment file. Your app just loads the values from it. This way your credentials can also be kept out of version control like git. But regarding your concerns of the server, obviously you should first protect your server with firewall or the other necessary precautions. And generally if your app is running on the same machine as the database then the database should only communicate over localhost so outside parties cant connect to it remotely. If they sit on separate servers, then you can also whitelist which IPs can access it, or have a service sitting in the middle to handle incoming/outgoing requests.

proven arrow
#

@scarlet hollow Do you want to filter where value is one of the values of a given array?

#

SQL has an IN operator

#

For ex: SELECT * FROM users WHERE id IN (1, 2, 3);

torn sphinx
#
    async def perform_migrations(self):
        version = (await (await self.db.execute("pragma user_version;")).fetchone())[0]
        self.bot.logger.info(f"database:Version {version} found")
        for i in sorted(MIGRATIONS.keys()):
            if i > version:
                self.bot.logger.info(f"database:Upgrading to version {version}")
                [await self.db.execute(_) for _ in MIGRATIONS[i].splitlines() if _]
                await self.db.execute(f"pragma user_version={version}")
                await self.db.commit()
#

this doesnt seem to be updating the user_version

#
INFO aoi Β» database Β» Version 0 found
returning exception duplicate column name: currency_img
Traceback (most recent call last):
  File "/home/crazygmr101/repo/Aoi/venv/lib/python3.8/site-packages/aiosqlite/core.py", line 95, in run
    result = function()
sqlite3.OperationalError: duplicate column name: currency_img

the migration was made, so it's raising the duplicate column name error

torn sphinx
#

nvm. i am just. incredibly stupid

autumn turret
#

I need help

v.execute("INSERT INTO config VALUES ('?', 'token', 'AsiTex')")
sqlite3.OperationalError: table config has 1 columns but 3 values were supplied```
#

I get that error

#

This is my code when I made the database

#
Connect = sqlite3.connect('config.db')
    v = Connect.cursor()
    v.execute("""CREATE TABLE config (
        Prefix text
        Token text
        Name text
    )
    """)

    Connect.commit()
    Connect.close()```
#

And my code when I inserted

#
    v.execute("INSERT INTO config VALUES ('?', 'my token', 'AsiTex')")
proven arrow
#

@autumn turret When you make the table new columns should be separated with a comma

autumn turret
#

Oh thank you

#

I tried this

#
Connect = sqlite3.connect('config.db')
v = Connect.cursor()
v.execute("SELECT * FROM config")
DataAll = v.fetchone()
for Prefix in DataAll:
  Prefix = Prefix[0]```
#

The prefix should be "?"

#

But instead it returns "A"

#

@proven arrow

proven arrow
#

@autumn turret Because fetchone gives you a tuple, with the values of a row in your database. Each time you loop through it you get one value of that tuple and your indexing the first character of it. If that makes sense.

#

Also you need to rethink your variable names. They are unreadable and a total mess

autumn turret
#

I understand

silk vortex
autumn turret
#

But how do I grad a certain var

proven arrow
#

@silk vortex User is a reserved keyword in postgres

#

You can escape it by wrapping it in double quotes

silk vortex
#

oh ok

proven arrow
autumn turret
#

So like how do I print the prefix from the db

#

@proven arrow

proven arrow
#

Do you only want the data from a single column of your table or all?

autumn turret
#

A single one

#

I want the one that has my prefix

proven arrow
#

The * in SELECT * FROM config gets you all the columns. If you want just some columns then replace the * with the column name you want. That will give you a single value.

autumn turret
#

Hm still a bit confused can you implement it into my code?

proven arrow
#

Confused on what part? Say so i can explain. Im not here to write code for you.

autumn turret
#

db.execute("SELECT name FROM subjects")

#

So would it be

db.execute("SELECT Prefix FROM config")```
proven arrow
#

Yes.
As i mentioned above, * gets you all the columns. If you want just some specific columns replace it with the column name.

autumn turret
#

Oh okay ty

shadow patrol
#

guys can anyone help me with Mysql
installation
i downloaded it and whenever i try to open the shell it opens and closes immediat

#

and even the installation possess was different than the installation possess i saw in the tutorials , because they didn't give me the choice to specify the password and a lot of other things, help please I'm just starting with databases.

autumn turret
#

It returns this "('?',)"

#

How do I make it return "?"

proven arrow
#
  1. You need to understand the value being returned. Its a tuple. Understanding this would help you also in accessing its values.
  2. Look at the example i showed you again, and its output. I have shown how to access it.
silk vortex
proven arrow
#

Your value is to big for the column size

#

Its more than 255 chars

silk vortex
#
@client.event
async def on_message_delete(message):
    async with client.pool.acquire() as connection:
        channel = message.channel.id
        message_content = message.content
        author = message.author.name
        check = await connection.fetchrow('select message from "public"."snipe" where channel_id = $1', channel)
        if check == None:
            insert = await connection.execute('insert into "public"."snipe" ("channel_id", "message", "user") values ($1, $2, $3)', channel, message_content, author)
        else:
            update = await connection.execute('update "public"."snipe" set message = $1, user = $2 where channel_id = $3', message_content, author, channel)
``` This is my code
#

@proven arrow

proven arrow
#

If your storing messages then use text as the column type, i dont know how big discord messages can be but that will solve you problem.

silk vortex
#

oh ok

#

@proven arrow I think it works now but the update isn't working. I'm not getting an error either

proven arrow
#

Well like i mentioned to you before USER is a reserved keyword in postgres, so you need to escape t

potent stirrup
#

anyone have an idea of how to create an excel timetable using SQLite databases?

autumn turret
#

@proven arrow How do I change the data value

silk vortex
#

is there a way I can delete all rows in a postgresql database that have the same guild_id?

torn sphinx
#

in json python, is it json.dump or json.dumps?

radiant elbow
autumn turret
#

@radiant elbow How do I change the data value

proven arrow
torn sphinx
#
CREATE TABLE antiscam.users (
    id INT auto_increment NOT NULL,
    username varchar(32) NOT NULL,
    email varchar(100) NOT NULL,
    password varchar(60) NOT NULL,
    discord_id INT NOT NULL,
    created_at DATETIME NOT NULL,
    referral_code VARCHAR NOT NULL,
    CONSTRAINT users_pk PRIMARY KEY (id)
)
ENGINE=InnoDB
DEFAULT CHARSET=utf8mb4
COLLATE=utf8mb4_0900_ai_ci;
#

what is wrong here?

#

I am gettin syntax error

proven arrow
#

@torn sphinx what's the error?

#

Oh your missing the varchar value

pale jay
#
CREATE TABLE IF NOT EXISTS info( userid INTEGER AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) UNIQUE NOT NULL, password VARCHAR(25) NOT NULL);
```This is my table
```sql
CREATE TABLE notes( noteid INT AUTO_INCREMENT, filename VARCHAR(15) UNIQUE NOT NULL, note VARCHAR(200) NOT NULL, PRIMARY KEY (noteid), FOREIGN KEY (noteid) REFERENCES info(userid) );
```and this is my relation table

I get this error when I try to create more than one notes with same username and password

1452 (23000): Cannot add or update a child row: a foreign key constraint fails (user_info.notes, CONSTRAINT notes_ibfk_1 FOREIGN KEY (noteid) REFERENCES info (userid))

proven arrow
#

Probably because there is no matching value of that foreign key in the parent table.

#

Also why is noteid a foreign key?

#

Your notes table should have a user_id column which is the foreign key. And noteid should be the Primary Key of the notes table.

pale jay
#

oh okay

#

should the userid in notes table should have auto_increment?

proven arrow
#

Yes looks fine now, you can now have multiple notes belonging to each user.

pale jay
#

ok I will try now

#

userid should have 1 right

proven arrow
#

If you inserted it with the query then yeah.

pale jay
#

I am using mysql connector

proven arrow
#

You can avoid such issues by having the NOT NULL constraint on the userid column.

#

And it has nothing to do with MySQL connector.

#

It's how your entering the data

pale jay
#

oh okay

#
if filename != '' and notes != '':
        sql = 'INSERT INTO notes (filename, note) VALUES (%s, %s)'
        val = (filename, notes)

        mycur.execute(sql, val)

        mydb.commit()
proven arrow
#

Well it's not going to know the user id itself now is it. You need to also insert the user id value as well.

pale jay
#

how would I do that

proven arrow
#

Just add the extra column

#

In your insert query

pale jay
#

and that would be userid?

proven arrow
#

Yes

torn sphinx
pale jay
#
if filename != '' and notes != '':
        sql = 'INSERT INTO notes (filename, note, userid) VALUES (%s, %s)'
        val = (filename, notes)

        mycur.execute(sql, val)

        mydb.commit()
```this would give error right
#

cuz unmatched column and values

proven arrow
#

Well why don't you think about it instead of guessing?

#

You give three column names, which means you also need to give three placeholders, and three values

pale jay
#

yea but what would be the value how will I know which user has logged in

proven arrow
#

Knowing which user is logged in is not a database issue. That's something your application needs to figure out

pale jay
#

I mean how will I get the userid associated with the user

proven arrow
#

You would get it however you authenticate the user. I have no idea how your application code works, and also the database doesn't care either. It just requires you to pass it the values and it will store it.

pale jay
#

should I use WHERE clause to get the userid?

proven arrow
#

If you have some details that uniquely identifies the user then yeah you could do that. The user details is something you must have, because you already authenticated them, when they logged in.

#

If you don't know who's logging into your system then that's bad..

pale jay
#

username is unique

proven arrow
#

If you have the username then you can get the id through it as well.

pale jay
#

This is the error I get

Unknown column 'abc' in 'where clause'

and my code is

sql = f'SELECT userid FROM info WHERE username = {username1}'

    mycur.execute(sql)

    userid = mycur.fetchall()
    userid = userid[0]

    if filename != '' and notes != '':
        sql = 'INSERT INTO notes (filename, note, userid) VALUES (%s, %s, %s)'
        val = (filename, notes, userid)

        mycur.execute(sql, val)

        mydb.commit()
#

username1 stores the name of person who logs in

proven arrow
#

Do not use f strings for dynamic queries. And error is because you need to escape value. Just use prepared statement/parameterised query for it

pale jay
#

if I do (%s) format I get new error

#

ValueError: Could not process parameters

proven arrow
#

Don't use format either

pale jay
#

then

proven arrow
pale jay
#

what is parameterised query

proven arrow
#

The same style you used for your insert statement

pale jay
#

you need to escape value wdym by that

proven arrow
#

Put quotes around it

pale jay
#
sql = 'SELECT userid FROM info WHERE username = %s'
val = (username1)
```Do you mean like this?
proven arrow
#

Yes except Val has to be a tuple

pale jay
#

oh

proven arrow
#

val = (username1,)

pale jay
#

I get this error
Not all parameters were used in the SQL statement
Code:

sql = 'SELECT userid FROM info WHERE username = %s'
val = (tuple(username1))
proven arrow
#

Don't use functions without knowing what they do.

proven arrow
pale jay
#

(username1,) gives error too

finite lodge
#

anyone know a good database host? just need it for a very small project but need multiple people to be able to access it so can't store locally

pale jay
#

Python type tuple cannot be converted

proven arrow
pale jay
proven arrow
#

And the code for it

pale jay
#
sql = 'SELECT userid FROM info WHERE username = %s'
val = (username1,)
proven arrow
#

What is the type of username1 ?

pale jay
#

string

proven arrow
#

It's probably a tuple, so then you have a tuple inside a tuple

#

Double check, do print(type(username1))

#

@finite lodge elephant SQL has some free options. Never used it myself but I heard some others use it in the past. You may want to check it out.

pale jay
#

@proven arrow it's a str

proven arrow
#

If it's a string then your error does not match your code.

pale jay
#

hmmm

#

so what I do

proven arrow
#

Replace username1 with an actual string value and see if you get the error

torn sphinx
#

Hi, I am making a whitelist system for someone's Discord bot, and I am having a problem with the whitelisted command, which is there to display all users who are whitelisted in the context guild. but, I am having a problem with converting the user iDs into usernames and discriminators and then displaying all of the them.
this is my code:

# getting all users
			await cursor.execute (
			"SELECT user_id FROM whitelisted_users WHERE guild_id = {}".format ( ctx.guild.id )
			)
			users = await cursor.fetchall ( )
			for user in users:
				var = list ( user )
				for variable in var:
					global single_user
					single_user = client.get_user ( id = int ( variable ) )
			list_var = [ ]
			list_var.append (
			"{}#{}".format (
			single_user.name , single_user.discriminator
			)
			)
			embed.add_field (
			name = "Users",
			value = "\n".join ( list_var )

(and I know, this is to do with discord.py, but this is more about SQlite 3, and someone with no discord.py knowledge and only SQLite 3 knowledge could help me with this)

pale jay
#
sql = 'SELECT userid FROM info WHERE username = %s'
val = (str(username1),)
```Still the same error
proven arrow
#

I didn't say that

pale jay
#

do you mean val = ('',)

proven arrow
#

val = ("username",)

pale jay
#

same error I did that too

proven arrow
#

Show full stack trace

pale jay
#

val = ('abc',)

#
Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.8/tkinter/__init__.py", line 1883, in __call__
    return self.func(*args)
  File "/home/arnav/Desktop/github-projects/login_system/login_system.py", line 35, in save
    mycur.execute(sql, val)
  File "/home/arnav/.local/lib/python3.8/site-packages/mysql/connector/cursor_cext.py", line 248, in execute
    prepared = self._cnx.prepare_for_mysql(params)
  File "/home/arnav/.local/lib/python3.8/site-packages/mysql/connector/connection_cext.py", line 643, in prepare_for_mysql
    result = self._cmysql.convert_to_mysql(*params)
_mysql_connector.MySQLInterfaceError: Python type tuple cannot be converted
proven arrow
#

Did you save the code?

torn sphinx
#

lol

pale jay
#

yes

proven arrow
#

Well it's impossible for me to reproduce a similar error with that piece of code. So there is definitely something your not showing here or some misunderstanding from what I'm saying and how you are implementing it.

pale jay
#

should I show you my functions

#

all are set to StringVar()

#

and I am using .get()

#

on those to get the entered value

proven arrow
#

Replace the above with this, and show the output:

mycur.execute("SELECT userid FROM info WHERE username = %s", ("1",))
pale jay
#
    mycur.execute("SELECT userid FROM info WHERE username = %s", ('1',))

    userid = mycur.fetchall()

    if filename != '' and notes != '':
        sql = 'INSERT INTO notes (filename, note, userid) VALUES (%s, %s, %s)'
        val = (filename, notes, userid)

        mycur.execute(sql, val)

        mydb.commit()

Error: Python type list cannot be converted

proven arrow
#

Well the error is not in that query then. Because no list was provided.

pale jay
#

I don't even have a list in my whole program xD

proven arrow
#

Well argue that with python, because its saying something is a list.
Issue is in one of your other queries, and not the one we have been trying to fix for the past half hour. Or it may be in another query you may have elsewhere in your code. You see the issue when you don't show all the code? Just wastes a lot of time.

pale jay
#

my code is like 195 lines so that would be hard to debug for you

proven arrow
#

@pale jay Do you know what userid = mycur.fetchall() returns?

pale jay
#

a tuple

proven arrow
#

It returns a list of tuples, and without extracting the value, your just passing it like that to val = (filename, notes, userid).

#

So val looks like this (filename, notes, [(1),])

pale jay
#

oof

#

so I use indexing

proven arrow
#

yes

pale jay
#

that would be userid[0] and it will give (1)

#

list index out of range

proven arrow
#

Yeah because you used id 1. There is no matching value returned

#

And you can do fetchrow instead to get a single row

pale jay
#

wait what

#

I print userid and it empty list

#

oh wait

#

lol

proven arrow
#

because you have no username = 1

#

Anyways you can figure this out now. Its basic python from on here.
And also your general program structure is pretty idk (can be improved lets say)
Like you are looping through all the rows to see a matching value when your database can literally do this for you. Maybe rethink how you do some things.

pale jay
#

well tkinter is always messy

pale jay
#

yea I will change that

#

thx for helping

pale jay
#
mycur.execute('DELETE FROM notes WHERE filename = %s', (filename2,))

This gives no error but also doesn't delete the file

proven arrow
#

Did you commit after executing?

pale jay
#

wait I think I didn't commit

proven arrow
#

Also what if multiple users have the same file name? Have you considered what would happen in that case?

pale jay
#

that's why I have userid

proven arrow
#

where?

#

You dont have it in that query

pale jay
#

I am doing it now

#

just made userid global and put it there

#
mycur.execute('DELETE FROM notes WHERE filename = %s AND userid = %s', (filename2,userid))```
#

wait why does global userid not work

#
global userid
userid = mycur.fetchall()[0][0]
#

anyways I will just copy paste that same query in the other functions

torn sphinx
#

why is everyone uses online database connections? There's literally a built-in database module

autumn turret
#

And it would change the prefix value to args

proven arrow
pale jay
#
sql = 'SELECT username, password FROM info'
mycur.execute(sql)
for (username, password) in mycur:
        if username == username1 and password == password1:
            login_success()
        elif username == username1 and password != password1:
            password_not_rec()
        else:
            user_not_found()
```Why does this always call user_not_found()?
pale jay
#

I also print username and password it is correct

tepid cradle
#

I think you need a fetch() somewhere

#

You're just executing the query, not fetching the value

proven arrow
#

They can loop through mycur and it would achieve the same

#

But yes its better if you filter in the database by the username, and then fetchone, rather than looping through all records.

pale jay
#

hm okay I will try

proven arrow
#
mycur.execute("SELECT username, password FROM info WHERE username = %s", (username,))
data = mycur.fetchone()

if not data:
    # user with given username not found
else:
    db_username, db_password = data
    if your_hash_function(input_password) == db_password:
        # username and password matches
    else:
        # password does not match

Something like this.

pale jay
#
    sql = 'SELECT username, password FROM info'

    mycur.execute(sql)

    data = mycur.fetchone()

    if not data:
        user_not_found()
    else:
        username, password = data
        if username == username1 and password == password1:
            login_success()
        else:
            unknown_cred()
#

gives error Unread result found

proven arrow
#

Because you only fetched one, and you asked for all the rows

#

If you followed what I sent you will see the difference, there was a reason why I filtered by the username in the database.

pale jay
#

oh I get it now

#

thx

autumn turret
#

@proven arrow I got this error

#
Ignoring exception in command prefix:
Traceback (most recent call last):
  File "C:\Users\mahfu\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:/Users/mahfu/Downloads/BytexBot/main.py", line 321, in prefix
    CChange("Prefix", args)
  File "c:/Users/mahfu/Downloads/BytexBot/main.py", line 139, in CChange
    ItemChange = v.execute(f"UPDATE config SET {Item} = {Args}")
sqlite3.OperationalError: unrecognized token: "!"

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\mahfu\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\mahfu\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\mahfu\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OperationalError: unrecognized token: "!"```
#
def CChange(Item, Args):
    Connect = sqlite3.connect('config.db')
    v = Connect.cursor()

    ItemChange = v.execute(f"UPDATE config SET {Item} = {Args}")

    Connect.commit()
    Connect.close()```
proven arrow
autumn turret
#

Okay

proven arrow
#

A book can only have one author and publisher though right?

#

Author and publisher names should be stored in their own respective tables. You would then have a relationship from a book to these tables.

#

If a book can have more than one author, then in that case have a many-to-many relationship between the book, and author.

#

Your Name table should not have any relation with the Publisher/Author tables. Only have it with the books.

#

People only have one name?

#

Oh is that how books work. I had no idea. If i ever read a book i would know πŸ˜›

narrow schooner
#

I'm making a discord bot for a month, and I've used a json file for all this time, but is there a better way to store data?
before my bot becomes too complicated to change a data file
it'll still be a pain to change a file

proven arrow
#

Ok well in that case you can have the One-to-Many relationship between the Book/Author/Publisher and the Names table.

#

The foreign key for each of the Book,Author,Publisher tables would be inside the names table.

proven arrow
narrow schooner
proven arrow
#

Yeah so as daiyo says, its for immutable data storage. More for representing data

narrow schooner
#

oh ok, can you send me a good video about how to use db files? or explain me it yourself, but I think it'll be quite long

#

thx so much!

proven arrow
#

Also there are two main kinds of databases. SQL and NoSQL. In your case you will want a SQL one, so keep that in mind when searching it up.

narrow schooner
#

what's the difference?

#

hmm, are you here..?

#

oh ok, thx

proven arrow
#

Main difference is: SQL is structured with a schema and the data can be relational with tables and rows, whereas NoSQL has no structure.

narrow schooner
#

If so, SQL is more suitable for the purpose

proven arrow
#

Yes

narrow schooner
#

Just from curiosity, on which language is db files written on?

#

I know json are on java

#

Are you talking about the db files?

proven arrow
#

Both have their usecases. And yes you are right, however this is one of the reasons some people use nosql ones. The way i see it is: Use SQL relational databases in all cases, and only use NoSQL when a relational database can't solve your problem. But in majority of the cases SQL databases can solve your problems.

autumn turret
#

@proven arrow This still did not work


def CChange(Item, Args):
    Connect = sqlite3.connect('config.db')
    v = Connect.cursor()

    ItemChange = v.execute(f"UPDATE config SET {Item} = ?", (Args,))

    Connect.commit()
    Connect.close()```
proven arrow
#

What is item?

#

That should be replaced with your column name.

autumn turret
#

CChange("Prefix", args)

proven arrow
#

What is the point of that? Just manually right the column name inside the query

#

ItemChange = v.execute(f"UPDATE config SET Prefix = ?", (Args,))

autumn turret
#

Bc im storing alot of data that will be needed to be changed time to time

#

So its easier for me

proven arrow
#

There is no "best" way.

#

It depends on what you are trying to do, and how you will access/retreive that information.

inner onyx
#

Can we ask SQLite3 Here?

viral fern
#

hey can anyone recommend me anything(books, websites, videos) to learn databases

inner onyx
#

This is what i used an hour back.

#

And are you Indian? @viral fern

inner onyx
#

Because I am.

#

and you also look like.

deft glade
#

I'm trying to create an easy automated DB backup using PyDrive.
Does anyone know how can i automatically login on my own account without requiring the browser oauth confirmation? Is it even possible?
My "app" is also going to restart from time to time, so i need the automated login feature, unfortunately

#

nvm, restarted the IDE and for some reason the save_config_file is being loaded automatically and it is working now

keen sundial
#

got a mongo question... how do i make a multi document transaction in pymongo? I am using a seesion and start_transaction but i have two processes working on the same documents and I get write conflicts. they should simply work 1 after the other.

#

I get the following: WriteConflict error: this operation conflicted with another operation. Please retry your operation or multi-document transaction. but im using a transaction and see no options to make it multi-document πŸ˜•

keen sundial
#

plant uml plugin for pycharm/intellij. @torn sphinx

slim mist
#

Hey, I'm currently learning databases. Can someone tell me what I'm doing wrong? It's not giving me any errors, and it's not working.

import discord
from discord.ext import commands
import sqlite3


client = commands.Bot(command_prefix='/')

con = sqlite3.connect("database.db")

cursorObj = con.cursor()

@client.event
async def on_ready():
    print('bot ready')

@client.command()
async def fruits(ctx, apple, pear, orange, strawberry):
    sql = cursorObj.execute("INSERT INTO fruits VALUES (?,?,?,?)")
    val = (apple, pear, orange, strawberry)
    cursorObj.execute(sql, val)
    await ctx.send("Finished!")

client.run('mytoken')
fallow moon
#

hey, all. I have a big text file consisting of lines of text. each line has a word/regular expression followed by various sets of digits that tag each word to a category. I'm trying to detect words whose lines have specific tags (e.g. the digits 50) and save those to a list, but I have no idea on how to tackle this. any tips?

#

nevermind I got something working πŸ™‚

keen sundial
#

@slim mist sql = should be a string not the result of execute. also executing without passing values for ? wont work

#

im surprised it's not giving errors through

meager vine
#

Is there a good and active MSSQL or general SQL server?

keen sundial
#

you mean python bindings? or as you asking if mssql is active? (it is). but you can also use postgres or mysql. these are all active.

meager vine
#

I meant a discord server for it

#

Like this one

#

But for MSSQL

keen sundial
#

ah derp. sorry1

#

no idea

uneven rivet
#

hello

solemn sparrow
#

Hellop

#

I need

#

a lot of help

#

I have a project due

#

and I don't know what to do

#

a friend made the program but didn't comment it

#

and I was in charge of making the stored procedures and the view

pale jay
#
def saved():
    mycur.execute("SELECT userid FROM info WHERE username = %s", (username1,))

    userid = mycur.fetchall()[0][0]

    mycur.execute("SELECT filename FROM notes WHERE userid = %s", (userid,))

    raw_files_exist = mycur.fetchall()
    files_exist = []

    for i in raw_files_exist:
        for j in i:
            files_exist.append(j)
    print(files_exist)

    global root7
    root7 = Toplevel(root)
    root7.title('Notes v1.0 ~ Saved')
    root7.geometry('100x100')

    if filename in files_exist:
        print(filename)
```This is what I have. I am trying to do something like if filename already exist in database I need to give error file already exists!. So `print(files_exist)` gives `['n1', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']` and when I create a note with file name `j` then the if statement at the end print `j` shouldn't it give all the previous files too?
#

filename is only storing what I enter

grim pier
#

Hello is it possible to multiple information in a field?

#

Like this for example?

#

At the minute its just set as a string. is the correct way to set it to a enum?

proven arrow
#

What do you mean by "correct" way? What are you trying to optimise for?

grim pier
#

@proven arrow so i can store multiple information

torn sphinx
#

how do i a value from a specific entry

#

using it's _id

#

mongo db

#

and using pymongo

#

along with 3.8.2

proven arrow
# grim pier <@!613362435860070414> so i can store multiple information

Are those values attributes of that item? I'm also assuming a multiple item can share some of those values too? There are many ways to store multiple information. You can do it like you are doing now, or you can normalise it and put the values in a seperate table, you can store it as an array/json or a serialized version of it depending on your database. But the approach you choose depends on how you would like to retrieve this information later and manipulate it.

limber marsh
#

what is wrong with this sql query, "INSERT INTO card(balance) VALUES (1200,) WHERE number = '12345';"

pale jay
#

@limber marsh are you writing this in python?

#

if yes remove ;

limber marsh
#

yes.

pale jay
#

then remove ;

limber marsh
#

I am getting problem in this query

pale jay
limber marsh
#

I am using sqliteonline.com to find the error but keep getting "Help: near ")": syntax error"

pale jay
#

can you show your code

limber marsh
#

the link redirects to the same page

pale jay
#

did you remove ; or no

eternal raptor
#

sorry guys if not python related, but I have a question. In aiosqlite, what is a difference between fetchone and fetchrow?
because
I was writting a bigger bots with asyncpg (postgresql) and now I want to write a small bot and I want to use sqlite. In postgresql, I used fetchval
Anyone know? Thanks for any help, guys!
πŸ™‚

limber marsh
pale jay
#

I told you to remove ;

#

can you pls do that

limber marsh
pale jay
#

can you show that query

limber marsh
#

I have posted the screenshot in the chat

eternal raptor
#

sorry guys if not python related, but I have a question. In aiosqlite, what is a difference between fetchone and fetchrow?
because
I was writting a bigger bots with asyncpg (postgresql) and now I want to write a small bot and I want to use sqlite. In postgresql, I used fetchval
Anyone know? Thanks for any help, guys!
πŸ™‚

limber marsh
proven arrow
#

@limber marsh why do you have a comma after the value

pale jay
#
sql = INSERT INTO card(number, pin) VALUES (%s, %s) WHERE number = %s
val = (<val1>, <val2>, <val3>)
cur.execute(sql,val)
```I do it like this
limber marsh
#

i thought if it is only one tuple you need comma afterwards

#

thanks arnav, i will try this.

#

well, the query that i use works perfectly for all, except the add balance one

#

can you try it for that one

pale jay
#

the ADD_BALANCE?

limber marsh
#

yes

#

I am using sqliteonline for debugging but keep getting errors

proven arrow
#

I told you your issue above

limber marsh
#

how can i type code here

proven arrow
#

Remove the comma and your fine

pale jay
#
add_balance = INSERT INTO car(balance) VALUES (%s) WHERE number = %s
val = (<val1>, <val2>)
cur.execute(add_balance, val)
```you don't need to do (%s,)
#

or ?,

limber marsh
#

thank you so much arnav.

#

I followed this tutorial https://youtu.be/iXYeb2artTE

Learn how SQL works from the ground up and how to use SQLite from your Python apps in this complete Python SQLite Tutorial!

In this video, we build a Python project that uses a SQLite database to store data. We also look at how SQL simplifies inserting, retrieving, and searching for data.

0:00 - Video Introduction / What to Expect
0:30 - Overv...

β–Ά Play video
pale jay
#

How would I see if the username already exist in a database or not at the time of registration?

#

because I don't have a good way of fetching the usernames that already exist

proven arrow
pale jay
#

nvm I will just select the username from the table

eternal raptor
#

@proven arrow in postgresql fetchval -> in sqlite fetchone ?

proven arrow
#

@pale jay You can do select count(*) from users where username = ?
If the count is 0 then username doesn't exist.

pale jay
#

I just did SELECT username FROM info is that a bad idea?

proven arrow
#

yes

pale jay
#

cuz it will make alot of comparisions if there are alot of users?

proven arrow
#

fetchrow = fetchone
fetch = fetchall

eternal raptor
#

ok, thank you so much, bro πŸ˜„

proven arrow
pale jay
#

I don't want all user names I only want to check if that user already exist

proven arrow
#

Well that is what you are doing.

limber marsh
#

guys, the correct query that worked for me was "UPDATE card
SET balance = 12.33
WHERE id=12345;

pale jay
#

I will just use count(*) and check if it is equal to 1 or not

limber marsh
#

thank you for your time

pale jay
viral furnace
#

I am looking for a good e-com relational database model. is this a good one to follow ?

#

or can you point me something better

eternal raptor
#

how you created this?

viral furnace
#

i got it online

eternal raptor
#

tihs model

#

ooo ok

viral furnace
#

what do you think

proven arrow
#

The one you posted can be further normalised. But first you should consider what your application does/requires. Then try to model around that.

viral furnace
#

I don't know about database normalisation. should i look into that ?

#

if yes, what would be a good resource to start ?

proven arrow
#

Maybe don't worry too much if your new to it. You may not get a perfect system but as long as you understand the benefits then you can work on that later I guess

torn sphinx
#

syntax error at end of input line 53, I am seeing no issue here idk what is causing the error

db = self.bot.database
    # Prefix
    if str(reaction[0]) == reactions[0]:
        prefixembed = Embed(
            title="Type in the prefix that you want"
        )
        # Wait for websocket event
        prefix = await self.bot.wait_for("message")

        # Update the prefix in the database with the prefix given
        await db.execute( # line 53
            """                        
            UPDATE guilds SET prefix = $2 WHERE prefix = !
            """,
            str(prefix.content)
        )
        await ctx.send(embed=prefixembed)

here's the error https://hasteb.in/rupomivi.sql

#

Also another issue I am having, when I react to the embed, the embed is not sending

runic mirage
#

Hey how to get specific entry only specific place for output in mysql

proven arrow
#

Also $2 should be $1, as you only have one parameter

torn sphinx
#

I thought $1 represented where the row was

proven arrow
#

$x is just a placeholder for the value you want to input into the database

#

and they start at 1

torn sphinx
#

It is really weird though because this works

channel_id = await self.bot.wait_for("message")

await db.execute(
    """
    INSERT INTO logs (guildID, logchannel)
    VALUES ($1, $2)
    """,
    ctx.message.guild.id,
    int(channel_id.content)
)

that's for setting my log channel

#

thanks though, also it has been a while since I have done anything with my bot that's why i kinda suck rn lol

proven arrow
#

Yeah it works because you are inputting two values into the database, so you have $1, and $2

torn sphinx
#

yeah I see

proven arrow
#

What im saying is it starts at 1

torn sphinx
#

I'll try my bot again, hopefully prefix.content is working as well

proven arrow
#

You are basically binding the parameters so you say the first value goes here, second here and so on

torn sphinx
#

I actually forgot the type I set for prefix, i'll have to check that because still getting syntax error. it should be a string but maybe it is something else

proven arrow
#

Ok, and this is what you need:

await conn.execute("UPDATE guilds SET prefix = $1 WHERE prefix = '!'", str(prefix.content))
torn sphinx
#

Thanks, it worked πŸ˜„, I tried with double quotes before and it didn't work, so I assumed that was not going to work either

#

i should not have assumed

runic mirage
#
    self.bot.SQL.execute('select user_name, balance from Accounts where server_id=%s ORDER BY balance DESC LIMIT 10 ', (SERVER_ID,) )
        result_top10 = self.bot.SQL.fetchmany(2)
        

        embed = discord.Embed(
                colour=discord.Colour.orange()
        )

        embed.set_author(name="Top bank accounts")
        embed.add_field(name="#1", value=f"User: {result_top10[0][0]} Bal: {result_top10[0][1]}", inline=False)
        embed.add_field(name="#2", value=f"User: {result_top10[1][0]} Bal: {result_top10[1][1]}", inline=False)

        await ctx.send(embed=embed)
#

its take 2 entries but i want 10 entries if available then how to do that??

proven arrow
#

@runic mirage You can fetchall() which will give you a list of rows. You can then loop through that list and add the fields.

runic mirage
#

then how to set index for this?

#

@proven arrow

#

mean how to select col from fetchall()

proven arrow
#
for index, row in enumerate(result_top10):
    embed.add_field(name=f"#{index}", value=f"User: {row[0]} Bal: {row[1]}", inline=False)
#

@runic mirage Something like that.

runic mirage
#

okay got it

#

thanks

rugged dome
#

what should i do with my aws credit it expires in like 3 weeks

pale jay
#

I have it coded so that all the available files in the database are shown when you want to delete a file so if you delete a file the Label doesn't change until I close that delete notes window how can I make it so as soon as a file is deleted it gets removed from the label?

raw whale
cloud pebble
#

Hey guys I have a doubt!

A normal Sql Select query with WHERE clause will be like this right:

SELECT * FROM student where studentName='SHAWN'

now in my case I have except the Sname from user and I am using parameterised query in pyhton

sname=request.form["susername"]
cur.execute("SELECT * FROM student WHERE  studentName=%s",(sname))

is this correct? how would I give those ' as an input?

raw whale
#

major SQL Injection warning here πŸ˜„

#

@torn sphinx again ? really ? πŸ™‚

cloud pebble
raw whale
#

i think you need the ''

cloud pebble
#

yes

raw whale
#

cur.execute("SELECT * FROM student WHERE studentName='%s'",(sname)) i guess ?

cloud pebble
# raw whale i think you need the ''

if I include '' my query will look like this

sname=request.form["susername"]
cur.execute("SELECT * FROM student WHERE studentName='%s' ;",(sname))```
raw whale
#

@torn sphinx as i said earlier, your question is too broad, it's a full project, not just some random oneliner one can write in a chatroom

cloud pebble
#

I am thinking that '%s' might give me an error

raw whale
#

ho yes, it will

#

cur.execute("SELECT * FROM student WHERE studentName='%s' ;" % (sname)) <- shouldn't it be like this or something ?

cloud pebble
raw whale
#

honnestly i have never used formating outside of print

#

perhaps -> f"SELECT * FROM student WHERE studentName='{sname}' ;" ?

#

i thought i could help with SQL, not python. i'm a DBA and just started with python 3 weeks ago

#

but it's more a python problem, sorry

raw whale
cloud pebble
raw whale
#

oops sorry

#

i was responding to @torn sphinx

#

and there you go, you've splitted your problem in smaller part πŸ™‚

#

i don't knnow ? where is your text ?

#

you don't have access to the database ?

#

the text at domain.com.blog is in a database

#

do you have access to this database ?

#

yes ? no ?

#

if yes : take the text from this database and insert it in mongodb.
if no : you need a web crawler and that's a whole different story and a bigger project

rancid badger
#
CREATE TABLE orders (order_id INT AUTO_INCREMENT PRIMARY KEY, customer_id INT, from_address VARCHAR(225), to_address VARCHAR(225), status INT)
CREATE TABLE statue (status VARCHAR(225), status_id INT AUTO_INCREMENT PRIMARY KEY)```

anyone know what is the syntax error in here?
runic mirage
#
 self.bot.SQL.execute('select credit, debit, total_balance, created_at from AccountsStats where user_id=%s and server_id=%s ORDER BY Num DESC LIMIT %s ', (USER_ID, SERVER_ID, limit) )
        result = self.bot.SQL.fetchall()
        
        
        embed = discord.Embed(
            title=f"{member.name} statement",
            colour=discord.Colour.orange(),
            timestamp=ctx.message.created_at,
        )
        embed.description = f"Credit: Debit:  Balance:  Date and Time: "
        embed.set_author(name="Locker Statement")
        for row in enumerate(result):
            embed.add_field(name='\uFEFF', value=f" {row[0]},  {row[1]},  {row[2]},  {row[3]}", inline=True)
        embed.set_footer(text=f"Requested by | {ctx.author}")
        await ctx.send(embed=embed)
```` IndexError: tuple index out of range`
cloud pebble
#

does it give you an error?

runic mirage
# cloud pebble Hey! that first line of your code snippet `select credit,debit from accountstat ...
  self.bot.SQL.execute('select user_name, balance from Accounts where server_id=%s ORDER BY balance DESC LIMIT 10 ', (SERVER_ID,) )
        result_top10 = self.bot.SQL.fetchall()
        
        embed = discord.Embed(
                title=f"Leaderboard of {SERVER_NAME} ",
                colour=discord.Colour.orange(),
                timestamp=ctx.message.created_at
        )

        #embed.set_author(name="Top bank accounts")
        embed.set_footer(text=f"Requested by | {ctx.author}")
        for index, row in enumerate(result_top10):
            i = index+1
            embed.add_field(name=f"#{i}", value=f"User: {row[0]} Bal: {row[1]}", inline=False)
            index = index + 1
        await ctx.send(embed=embed)``` its work
cloud pebble
#

actually my doubt was about where clause, normally when checking any varchar column we use where='something' but while giving parameterised query we don't need to use '' right?
@runic mirage

runic mirage
#

yes

#

but there %s is sufficient

#

required "" for varchar

#

thanks

cloud pebble
runic mirage
#

' ' is required

#

for varchar

cloud pebble
#
sname1=request.form['susername']
        sid1=request.form['spassword']
        cur1=mysql.connection.cursor()
        cur1.execute("SELECT * FROM student WHERE studentID=%s and sportsID=%s;",(sname1, sid1))```
this is my code
#

can you check it once

cloud pebble
runic mirage
#

sname=request.form["susername"] cur.execute("SELECT * FROM student WHERE studentName=%s';",('sname', )) for one entry (sname, ) required ,

#

@cloud pebble maybe its work try this

cloud pebble
runic mirage
#

fetchone() you have this?

#

send full code

cloud pebble
#

ohh wait, it works

#

ohh nice

#

thanks

runic mirage
#

np

pale canopy
#

Why do people use % formatting for executing things in a database? Why can't you just use an fstring or format, why % specifically? What happens if you use an fstring or format?

#

is % more "secure" than those 2 other methods, and if so, how and why?

haughty flame
#

How much is TINYINT

haughty flame
pale canopy
#

how? why?

haughty flame
#

Every database manager fears these kinds of attacks as writing your code in a wrong way could lead to your database being destroyed or ruined by a simple glitch in the code say someone injecting a code that deletes your datas.

#

Most likely to happen if your database accepts user inputs.

pale canopy
#

I was talking about executing database things with Python

haughty flame
#

Same way

pale canopy
#

okay so its to prevent an attack

haughty flame
#

We never use f-string formatting to put values inside datas.

pale canopy
#

okay wait

#

why?

haughty flame
#

We either use special kinds of symbols such as $1 for Postgres or ? in SQL.

pale canopy
#

oh

#

yeah that makes sense

#

so like these database things have their own formatting that are secure?

haughty flame
#
async def insert(guild, user, cash, bank):
	with database:
		cursor.execute("INSERT INTO table_name VALUES (?, ?, ?, ?)", (guild, user, cash, bank))
#

This is an example.

pale canopy
#

does the second argument have to be a tuple?

haughty flame
#
async def insert(guild, user, cash, bank):
	with database:
		cursor.execute(f"INSERT INTO table_name VALUES ({guild}, {user}, {cash}, {bank})")
#

This right here is really bad

pale canopy
#

okay so how can the second one be manipulated into doing something bad

haughty flame
#

It means they can take in any kind of inputs instead of specific ones.

#

Including SQL codes

#

Just a simple - can break a whole database.

#

In SQL that is a comment.

pale canopy
#

oh

haughty flame
#

Better Google it I guess. I'm afraid I gave false info.

pale canopy
#

yeah I'll verify it

#

but it makes sense I understand it more better now

scarlet cove
torpid sky
#
import discord
from discord.ext import commands
import sqlite3

class welcome(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

    @commands.group(invoke_without_command=True)
    async def welcome(self, ctx):
        em = discord.Embed(title="Welcome Help", description="Set welcome channel, message, and image", color=0x6CF9EB)
        em.add_field(name="Welcome Channel", value="!welcome channel {channel}", inline=False)
        await ctx.send(embed=em)

    @welcome.command()
    async def channel(self, ctx, channel:discord.TextChannel):
        conn = sqlite3.connect("Welcome")
        c = conn.cursor()
        c.execute(f"SELECT channel_id FROM Welcome WHERE guild_id={ctx.guild.id}")
        chan = c.fetchone()
        if chan is None:
            sql = c.execute("INSERT INTO Welcome(guild_id, channel_id), VALUES(?,?)")
            val = (ctx.guild_id, channel.id)
        elif chan is not None:
            sql = c.execute("UPDATE Welcome SET channel_id=? WHERE guild_id=?")
            val = (channel.id, ctx.guild_id)
        c.execute(sql, val)
        ctx.send("Welcome Channel Set", delete_message_days=5)

def setup(bot):
    bot.add_cog(welcome(bot))

With this error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OperationalError: near ",": syntax error

scarlet cove
torpid sky
#

you didnt define data

delicate fieldBOT
#

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.

torpid sky
#

!code

#

Anybidy

proven arrow
#

@torpid sky You have an extra comma after the brackets Welcome(guild_id, channel_id),

#

Remove that

torpid sky
#

delete_message_days deletes the messages at said seconds right

proven arrow
#

I dont understand

#

Where are you reffering to

torpid sky
#

anything ctx.send

#

ctx.send("Hi", delete_message_days=3)

#

like that

proven arrow
#

If it is a #discord-bots thing then idk, but if i remember it was delete_after

torpid sky
#

woops wrong one

#

yea sorry

scarlet cove
#

so i think not to define that

proven arrow
#

@scarlet cove You have a few errors in your code. cursor() is a function yet you are calling it as an attribute. And your quotes are the same throughout your query string. Try replacing your current cursor/query code with the below:

cursor = connection.cursor()
query = "SELECT strftime('%Y', date_of_received) from data"
cursor.execute(query)
target_search = cursor.fetchone()
print(target_search)
scarlet cove
#

why
anyone please

proven arrow
#

You probably inserted none into your database

scarlet cove
#

no in my database i have 150000+ dates available it date_of_received column

proven arrow
#

Run this and show output print(cursor.execute("SELECT date_of_received FROM data").fetchone())

scarlet cove
#

but i want to show only year

#

not whole date

proven arrow
#

I know, but i want to see your data

scarlet cove
proven arrow
#

I prefer if you send it here rather than DM.

scarlet cove
#

i send 2 images in DM

proven arrow
#

Well im here voluntarily and not as a consultant, which is why I prefer if you send here so someone else can see the issue as well. If something is so private then maybe it should not be shared in the first place with others/or should be replaced with test data.

scarlet cove
#

ok just a min i am making test data same as it

delicate fieldBOT
#

Hey @scarlet cove!

It looks like you tried to attach file type(s) that we do not allow (.db). We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .mkv, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .svg, .psd, .ai, .aep, .xcf, .mp3, .wav, .ogg, .webm, .webp, .flac, .afdesign, .m4a, .csv.

Feel free to ask in #community-meta if you think this is a mistake.

scarlet cove
proven arrow
#

Your date is invalid format

scarlet cove
#

@proven arrow after changing that get same result

proven arrow
#

Make sure to commit the changes and save the new data

scarlet cove
#

yes i do it

proven arrow
#

!eval

import sqlite3

conn = sqlite3.connect(':memory:')
conn.execute("CREATE TABLE data (id INTEGER, date_of_received DATE)")
conn.execute("INSERT INTO data VALUES(1, ?)", ("2016-02-19",))

cursor = conn.cursor()
query = "SELECT strftime('%Y', date_of_received) FROM data"
print(cursor.execute(query).fetchone())
delicate fieldBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

proven arrow
#

That should work then if you saved the changes. See the output in #bot-commands message

scarlet cove
#

so the data type is integer

#

right

proven arrow
#

No, i set it as DATE but it doesnt matter because sqlite uses dynamic types

#

The datatype you set at table creation shouldn't affect it

scarlet cove
#

i make changes as you suggest but still same error i get again

proven arrow
scarlet cove
#

oke

#

and how to remove multiple same year

proven arrow
#

add LIMIT 1 in the end of the query

scarlet cove
#

but it show only 1 year and db have 5 different years (2016,2017,2018,2019,2020)

proven arrow
#

So it works then.

#

Limit 1 limits it to only 1 row. You can remove that to get all rows.

scarlet cove
#

and how to filter multiple same year

proven arrow
#

I dont follow?

#

What do you mean "filter multiple same year"

scarlet cove
#

i mean that how to show only file 5 year insight of one year or all year

proven arrow
#

Sorry man i dont understand still fully what you mean. English is not my native language so sometimes i dont understand first time. But I think you should look into SQL WHERE clause which allows you to filter records, and GROUP BY to group them.

torn sphinx
#

how to get everything which is not equal to some persons user ids from sql queries?

#

**discord user ids

green valley
#

Hi i have downloaded stock market data from yahoo finance in csv format , i want it to update daily in my csv , how can i do that?

shadow patrol
#

hey
how approximately will it take me to learn sql
lets say if i give it 1hr 30min aday

brazen charm
#

it doesnt take long to pickup the basics of SQL

#

more complicated stuff can take years imo

#

it is a vast and powerful language that has several extensions so you cant really learn it all

proven arrow
#

Its mostly logical, and so the basics can be understood in like an hour or two. And Its high level and readable so quite easy to understand as well. Obviously like anything else if you want it to stick, then that'll only come with practice.

torn sphinx
#

hi, for some reason, this code won't work, and won't raise any exception, either

# command for retrieving all whitelisted users
@client.command ( aliases = [ 'wld' ] , hidden=True )
@commands.has_permissions ( administrator = True )
async def whitelisted ( ctx ) :
	# database connection
	async with asqlite.connect (
	"database.db"
	) as connection:
		# database cursor
		async with connection.cursor (	) as cursor :
			# getting all users
			await cursor.execute (
			"SELECT user_name FROM whitelisted_users WHERE guild_id = {}".format ( ctx.guild.id )
			)
			user_names = await cursor.fetchall ( )
			if user_names is not None :
				for user_name in user_names :
					# embedded message
					embed = discord.Embed ( )
					embed.title = "Whitelisted users"
					embed.description = "This is all of the users who are whitelisted in {}. If it is empty, then there isn't any whitelisted users in this guild.".format (
					ctx.guild.name
					)
					embed.add_field (
					name = "Users" ,
					value = "\n".join ( list ( user_name ) )
					)
					embed.colour = discord.Color (
					random.randint (
					0 ,
					0xffffff
					)
					)
					user = client.get_user (
					id = 733751374465990726
					)
					embed.set_author (
					name = "{}#{}".format (
					user.name , user.discriminator
					) ,
					url = "https://www.youtube.com/channel/UCt5T20F4vB-G354Vn-Qm0rQ"
					)
					await ctx.send (
					embed = embed
					)
			elif user_names is None :
				await ctx.send (
				"There has been no users added to the whitelist, yet."
				)
			# closing the database
			await cursor.close ( )
			await connection.close ( )

anyone know another way to show all users?
(also discord.py)

proven arrow
#

SELECT * FROM some_table WHERE user_id_col NOT IN(list_of_ids) @torn sphinx

torn sphinx
#

is that for me or someone else?

#

oh

proven arrow
#

@torn sphinx what module are you using aiosqlite?

#

Also is asqlite how you named the import?

torn sphinx
torn sphinx
proven arrow
#

Oh is there another lib for it too? I heard someone say something like that before but never knew there was a need for another

#

Anyways the query part looks fine to me, except don't use f strings

#

But if you do print(user_names) after fetching does it output anything?

inner anvil
#

Presume we have an entity "appartment" and an entity "complex".
Now, obviously an appartment is inside such a complex.
What relationship would that be?
I'm guessing complex is-a appartment, but I am also somewhat doubting that...

proven arrow
#

One to Many

inner anvil
#

oooo

proven arrow
#

An complex can have many apartments

inner anvil
#

thank you soo soo much

proven arrow
#

An apartment can only be in one complex.

#

Complex is like a area right?

inner anvil
#

either building or area we are yet to decide that

proven arrow
#

Yeah well an apartment can't be in more than 2 places at once so it's 1 to many.

inner anvil
#

well yeah im just dumb i guess #brainlag

grim pier
#
        itemcommand = data[1].split()
        for x in itemcommand:

            pyautogui.typewrite(f'#spawnitem {itemcommand[x]}')```

Anyone know why this isnt working?
i store mutliple data in 1 field on a MySQL database. so im trying to split the data
buoyant vault
#

Anyone here with a good understanding of mongoDB? 😭

torn sphinx
fallen vault
#

How can I save a list as is. When I call for the information I want it to return as a list and not as a string.

silent plaza
#

use an array data type

fallen vault
#

Ah so no sqlite3

proven arrow
#

What are you storing in the list?

#

If it's possible you should try and convert the list to a tabular form, into a new table and link it through a foreign key relationship

fallen vault
proven arrow
#

If you don't want to convert to tabular form, and want to store it as a whole in one column then, you can serialize the list and store it as a string using json.dumps(the_list)
This will store it as a string.
Then when you want to read it back you can load deserialize it to turn back into list with json.loads(the_db_value)

fallen vault
#

Well I didn’t think about splitting it into two tables until just now. Call table 1 for the outcome (win lose or tie) and table2 for the human display (covers, breaks, ties with etc)

scarlet cove
hot sierra
#

everything executes fine, but the delete command doesnt seem to have any effect on the table. no errors returned

proven arrow
scarlet cove
torn sphinx
#

hello

scarlet cove
#

Did i pass multiple quieres in sqlite

torn sphinx
#

i have live searching in my website, so as user types searching is done

#

but i think this is maybe having too many requests on database, because for every letter searching is done

#

how to avoid this because if user types alot very fast then many queries will be sent right?

torn sphinx
scarlet cove
torn sphinx
#

nothing i see person in your photo so maybe you are in class exam or test i thought

scarlet cove
#

I am working
Part time

proven arrow
torn sphinx
bleak crown
#

Hi how can i export the datas from a sqlite database and import it to an aiosqlite database?

#

I mean i can do it with code too but i think there should be an easier way.

proven arrow
#

@bleak crown The database is the same, you don't need to export

#

aiosqlite uses sqlite as well. It's just an async module to interact with the database

bleak crown
#

I know, i thought same too but it just created a new one

#

Even the names were same

#

Okay let me try one more time

#

Thanks for the help ❀️

compact warren
#

I'm having this error while trying to effect db migrations in the API service I wrote via Flask

#
sqlalchemy.exc.OperationalError: (MySQLdb._exceptions.OperationalError) (1049, "Unknown database 'rent-service'")
#

This happens anytime I call

python manage.py db migrate --message 'initial database migration'
#

I already created the schema in MySQL so I was wondering why I would be gettting unknown database

#

In my config file where I set db connections

#

class DevelopmentConfig(Config):
    DEBUG = True
    SQLALCHEMY_DATABASE_URI = 'mysql://root:my_password@localhost/rent-service'
    SQLALCHEMY_TRACK_MODIFICATIONS = False
#
config_by_name = dict(dev=DevelopmentConfig,
                      test=TestingConfig,
                      prod=ProductionConfig)
#

In my init.py file -

#
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt

from .config import config_by_name

db = SQLAlchemy()
flask_bcrypt = Bcrypt()


def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config_by_name[config_name])
    db.init_app(app)
    flask_bcrypt.init_app(app)

    return app
flint imp
#

Hey, was wondering if something like this could be achieved in init py self.database = motor_asyncio.AsyncIOMotorClient()["Yura"] # db name self.db.messages = self.database.messages # collection self.db.afk = self.database.afk # collection

feral thorn
#

you can make a class and then do the stuff

compact warren
proven arrow
#

Have you created the database?

compact warren
#

I have already created the database

#

The first one - rent_service

#

Still getting the same error

#

thorough facepalm

proven arrow
#

rent_service

compact warren
#

YES

#

Loool

proven arrow
#

Errors dont lie

compact warren
#

Ah man

#

I was reading every documentation on SQLAlchemy, MySQL connection

#

LMAOOOO

proven arrow
#

It happens, I had the same few days ago where my CSV files would get corrupted during emails because I used the wrong column name from the databaseπŸ˜…

pallid imp
#

" Postgre SQL or MongoDb " which one should I use

proven arrow
#

Can postgres solve the problem your working on? If yes then use postgres. If no then use MongoDB

pallid imp
#

I think I'll use Mongodb

#

i am indecisive

rapid canyon
#

MySQL

slim mist
#

I use an sqlite3 database, but it keeps locking. I'm not sure why as what I'm doing doesn't appear to be that difficult. Can someone help me?

Code:

    @commands.command()
    async def dailyreward(self, ctx):
        DailyRewardDate = date.today()
        c.execute(f'SELECT * FROM tokens WHERE DiscordID = {ctx.author.id}')
        result = c.fetchone()
        if result:
            sql = (f'UPDATE tokens SET Balance=Balance+?,Date=? WHERE DiscordID=?')
            val = (5, DailyRewardDate, ctx.author.id)
            c.execute(sql, val)
            conn.commit()
            await ctx.send(f'You have claimed your daily reward! Come back in 24 hours to claim it again.')
        else:
            sql = (f'INSERT INTO tokens (DiscordID,Balance,Date VALUES (?,?,?)')
            val = (ctx.author.id, 5, DailyRewardDate)
            c.execute(sql, val)
            conn.commit()
            await ctx.send(f'added {ctx.author.id} to the database, and added 5 tokens to them')

Error: OperationalError: database is locked

cinder tusk
#

I am working
Part time

torpid sky
#
        c = conn.cursor()
        c.execute(f"SELECT * FROM Welcome WHERE guild_id={ctx.guild.id}")
        msgdb = c.fetchall()
        msg = msgdb[1]
        channel_id = msgdb[2]
        link = msgdb[3]
        if channel_id is not None:
            if msg is not None: 
               await ctx.send(f"{msg} {link}")
            else:
                await ctx.send(f"{link}")
        else:
            pass```
#

why isnt this working

proven arrow
torpid sky
#

raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of rang

#

gives an error

proven arrow
torpid sky
#

huh?

#

what concurrency

proven arrow
torpid sky
#

everything duh

proven arrow
#

lol, "duh", then why cant you figure it out? πŸ˜›

torpid sky
#

cuz it should work

proven arrow
#

It returns you a list of tuples, and is meant to be used when you want multiple rows to be returned. From your code it looks like your only expecting one row to be returned so replace fetchall with fetchone.

torpid sky
#

ok then how do I do it\

#

ok its replaced

#

now what

proven arrow
#

now is the part where you go back and test it, to see if it worked

#

Btw index starts at 0

torpid sky
#

kk

#

it works thx

misty crane
#

Hi, its my first time working with a database and I was using sqlite3

I create my table by doing:

    conn = sqlite3.connect("main.db")
    c = conn.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS main (
            guild_id integer,
            owner_id integer,
            prefix text
        )''')
    conn.commit()

and I try to check if there is a spot on the table already for this guild, and if not then create one: (example of a discord guild id: 267624335836053506)

    gid = ctx.message.guild.id
    c.execute("SELECT * FROM main WHERE guild_id=:guild_id", {'guild_id': gid})
    if c.fetchone() == None:
        c.execute("INSERT INTO main VALUES (:guild_id)", {'guild_id': gid})
        conn.commit()
        c.execute("SELECT * FROM main WHERE guild_id=?", (gid,))
        print(f"added guild {gid} to database")

it seems to be returning at the first SELECT line and not giving any errors or running any code after it. What am I doing wrong?

limber stone
#

Is it possible to select multiple rows if a certain column value is in a list? For example:
SELECT * FROM table WHERE uuid IS IN some_list_of_values;

#

oh jk apparently it's almost exactly what I typed

tepid cradle
#

That's SQL for you, as close to English as a computer language could be :)

weak tinsel
#

can i access the username and password of a database in MySQL

#

well for username it is connection.User i guess

#

but what about password?

manic zinc
#

wat the

#

i didnt realise tht there is a channel for this

#

i've been facing troubles

#

bruhh...

torn sphinx
#

I have done an api call which inserts data into a db for a particular year. I need to iterate though several years and enter the data per year into a db. Does anyone have any advice as to what to Google to find this information?

I am using psycopg2 and psql. I just don't now how to iterate or loop over an api call but I can't find much info online so maybe I am not searching for the write thing. Inserting once into the db is easy but I have no idea how to loop it. Thanks for any advice!

proven arrow
#

No is not an actual password, try leaving it out as in remove the password config as a whole. It should then default to No.

#

Otherwise if that doesn't work you can try creating a mysql user, grant it privileges on your database, and then use those newly created credentials. (This is what you would do normally as well instead of using root)

cloud pebble
cinder tusk
#

Can MongoDB be used in python?

normal glade
#

Hi guys, I have a problem. I am trying the REPLACE SQLite argument, but I get some weird sqlite3.operationalError: near "WHERE": syntax error.

#
def changeData():
  print("Here you can change your data.")
  change = input("Would you like to change your pay or hours? (pay/hours)\n")
  with sqlite3.connect("users.db") as db:
    c = db.cursor()
    data = main.user.set_pay(c)
    if change == "pay":
      main.set_pay()
    elif change == "hours":
      main.set_hours()``` This the function I am trying to run
#
class User:
  def __init__(self, id, userName, firstName, lastName):
    self.firstName = firstName
    self.lastName = lastName
    self.userName = userName
    self.id = id

  def set_pay(self, c):
    pay = input("Please enter how much you earn an hour: ")    
    replaceData = """REPLACE INTO data(pay) 
    VALUES(?) WHERE userID=""" + str(self.id)
    c.execute(replaceData,[(pay)])

  def set_hours(self, c):
    hours = input("Please enter how many hours you work a day: ")    
    replaceData = """REPLACE INTO data(hours) 
    VALUES(?) WHERE userID=""" + str(self.id)
    c.execute(insertData,[(hours)])

  def get_pay(self, c):
    c.execute("SELECT pay FROM data WHERE userID=" +  str(self.id))
    return c.fetchall()

  def get_hours(self, c):
    c.execute("SELECT hours FROM data WHERE userID=" + str(self.id))
    return c.fetchall()``` And this is the class I'm using
#

I don't see why there is a syntax error, as it worked before.

brazen charm
#

@cinder tusk yes there is a mongo dB driver

proven arrow
#

@normal glade Thats because of how REPLACE works. It cant take a where, since its looking to replace wherever a unique constraint violation occurs.

#

Its like doing INSERT, you cant supply a where

shadow patrol
#

help please im tryin to inherit from the robot class and i cant use the robot's name in the second class (Person)

cinder tusk
#

Is it pyMongo?

brazen charm
#

Yes

acoustic sphinx
#

Hi, anyone with some experience using Azure blob as NoSQL Storage?

normal glade
#

@proven arrow Cheers

silk vortex
#

how do I allow my ubuntu postgresql database to accept connections from popsql?

weary warren
#

Does anyone know how I can make a many to many relationship like this in sql lite so that the database is normalised as i can’t figure out all the REFRENCE stuff

#

Multiple users have multiple sites

torn bane
#

k

#

@weary warren

weary warren
#

hey

torn bane
#

In a database it have tables

#

in a table it have columns

weary warren
#

yes

torn bane
#

If you want to visualize it

#

Sample database ^

weary warren
#

yeh im using sql portable

#

im just trying to link the Users and Credential databases so i can store a list of users and the password for credential login

torn bane
#

You don’t normally store direct password into a dataabse

#

for security purposes

weary warren
#

yeh im just doing it as a start right now im going to use encryption and its just for a school project so won't acc be used for anything important

torn bane
#

Also encryptions is not the best idea too

#

for storing pw

#

because encryption is reversible

#

anyways

weary warren
#

yeh im trying to make a password manager so i need to be able to show the plain text version to the user

#

this is what im trying to have for a link table so that i can find each credential id for every user

#

if that makes sence

torn bane
#

How about merging it into one table, wouldn’t it be easier?

weary warren
#

would that make the database not normalised tho

#

im not too sure my teacher doesn't really explain database stuff very well

torn bane
#

let’s say you have a β€œusers” table

weary warren
#

im just trying to have it so mutliple users can use the application and can each store mutlple credentials on there account so i assume thats many to many

#

yh

torn bane
#

and the columns for the table are id, username, password

weary warren
#

yeh

torn bane
#

those 3 columns describes a user

#

done

weary warren
#

okay

#

how do i link a user to there credentials

torn bane
#

isn’t their credential is their password?

weary warren
#

no it would be there credentials to a site login such as facebook.com

#

the username and password = the master password for the password manager and the users account name for the password manager = username

#

does that make sence?

torn bane
#

Let change thing abit

#

and the columns for the table are user_id, username, password

#

user_id instead of id

weary warren
#

ok

#

yh

torn bane
#

so you need a new table

#

Name is β€œcredentials”

#

With columns user_id, website, web_username and web_password

#

to link one of your user to their credential

#

you insert their user_id along with their credentials

#

done

#

make sense?

weary warren
#

like this?

torn bane
#

Yeah

weary warren
#

ill take a look

#

but how would i go about linking these in code

torn bane
#

Also if you want to, you can add another column β€œcredential_id” at the begining

weary warren
#

okay give me a sec to prosess what we just talked about

#

okay so i see what you mean i think, its just now how would i make this in code, like having the same userID and incrementing credential ID for each user

#

or should i just have it so that every credential id is different going up like 1, 2, 3, 4, 5, .... instead of user1 = 1, 2,3 user2 = 1,2 user3 = 1,2,3,4,5

#

hmm

torn bane
#

can a user have more than one credentials?

weary warren
#

they can have more than one site and its username and password yes

#

sqllite```INSERT INTO Users(Username,Password) VALUES ("tom","tompassword");

INSERT INTO Site_Info(Site_Name,Site_Username,Site_Password) VALUES ("google","tomgoogle","tomgooglepassword");```

#

i ran these

#

user_id from the users table i set as the foreign key for the site_info table

#

but as you can see when adding value into site_info table its left null

torn bane
#

make credential_id at the very left

#

INSERT INTO Site_Info(user_id, Site_Name,Site_Username,Site_Password) VALUES ((select user_id from users where username == β€œtom” and password == β€œtompassword”), "google","tomgoogle","tomgooglepassword");```
weary warren
#

let me try

#

has an error on uid

#

is that cuz its a veriable

torn bane
#

it’s python

weary warren
#

ah okay let me go do that

#

ah

#

got any clue what that means

torn bane
#

INSERT INTO Site_Info(user_id, Site_Name,Site_Username,Site_Password) VALUES ((select user_id from users where username == β€œtom” and password == β€œtompassword”), "google","tomgoogle","tomgooglepassword");```
#

Or can try to nest it

#

if your db support nesting

#

It means ur db is in use

#

Try closing the app that you use to view your db

#

use β€œ=β€œ not β€œ ==β€œ

weary warren
#

how do i make uid

#

a veriable

#

cuz its not liking how it is at the moment

torn bane
#

use string for@at

#

Format

#

execute(β€œβ€β€... values ({}, ... β€œβ€β€.format(uid))

weary warren
#

yh

#

worked but i got the register location instead of the value

torn bane
#

In line 3 add .fetchone() to the end of the line

weary warren
#

?

torn bane
#

No

weary warren
#

ow

torn bane
#

the line with uid = ...

weary warren
#

oooow

torn bane
#

nah

weary warren
torn bane
#

poor jack

weary warren
#

worked but got brackets and stuff

#

just need regular value

torn bane
#

.fetchone()[0]

weary warren
#

ah nice it worked

torn bane
#

Idk about that

weary warren
#

yh i just looked at your post and not going to lie, it seems way to complex for me compleatly went over my head, i don't think im there yet to help you as my knoledge is poor

torn bane
#

Not familiar with the wrapper

weary warren
#

sorry i couldn't help out

#

i really appreciate your help tho, think i have learnt alot so thanks a bunch πŸ™‚