T
T
timka2282021-03-21 12:06:17
Python
timka228, 2021-03-21 12:06:17

How to replace certain values ​​in sqlite3 db with python 3?

There is a user database on sqlite3, and there is a Python 3 script that works with this database. I need the script to replace certain values ​​for all users (rows) in a certain column with another one. That is, for example, there are n-th number of users (rows), there is a status column, and for each user this status can be blocked or normal. For some it is blocked, for others it is normal. And the script should iterate over all users (all rows in the status column), and replace those who had the blocked status with normal. And I also need information about the entire line where the replacement occurs so that the script can send a message to the user about the change in his state.
Please help me with this please. How to iterate through the lines and search for the right ones?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Karbivnichy, 2021-03-21
@timka228

Play:

import sqlite3

conn = sqlite3.connect('users.db')
cursor = conn.cursor()

cursor.execute('''CREATE TABLE IF NOT EXISTS users(id INTEGER PRIMARY KEY AUTOINCREMENT,
                                                    user_name TEXT,
                                                    user_id TEXT,
                                                    user_status TEXT
                                                )''')

cursor.execute('DELETE FROM users')

users = 

for user in users:
    cursor.execute('INSERT INTO users VALUES(?,?,?,?)',user) # Заполняем таблицу из списка
conn.commit()

result = cursor.execute('SELECT id,user_id FROM users WHERE user_status="blocked"').fetchall()
# Выбираем из базы id(порядковый номер пользователя в базе), user_id - id пользователя в вашей системе только тех пользователей,
# в которыъ статус blocked

for x in result: # перебираем результаты
    id,user_id = x # Распаковываем кортеж
    cursor.execute('UPDATE users SET user_status=? WHERE id=?',('normal',id)) # обновляем записи в таблице.
    # Так как у нас есть порядковый номер пользователя в таблице(id), то обновляем записи этих id и устанавливаем
    #  user_status в normal
    print(f'Статус blocked изменен на normal для следуещего пользователя {user_id}')

conn.commit()
conn.close()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question