V
V
Vadimganin2022-04-02 11:47:39
Python
Vadimganin, 2022-04-02 11:47:39

How to create new columns in SQLite3?

How to create new columns without errors and losing the old database?
For example, I created a database after running the file, I can no longer create a new column, there will be an error

Here is an example code:

import sqlite3

db = sqlite3.connect('the_server.db')
sql = db.cursor()

sql.execute("""CREATE TABLE IF NOT EXISTS users (
  login TEXT,
  password TEXT,
  cash BIGINT
)""")

db.commit()

user_login = input('Login: ')
user_password = input('Password: ')

sql.execute(f"SELECT login FROM users WHERE login = '{user_login}'")
if sql.fetchone() is None:
   sql.execute(f"INSERT INTO users VALUES (?, ?, ?)", (user_login, user_password, 0))
   db.commit()

   print('You are loggined!')
else:
  print('This account already exists!')

  for value in sql.execute("SELECT * FROM users"):
    print(value)


Imagine that someone registered and after that you added a column (for example, description TEXT) and you can no longer register, there will be an error that there are only 3 columns, and you register with 4 fields

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
denislysenko, 2022-04-02
@Vadimganin

table_name is the name of the table you want to add the column to
column_name is the name of the column you want to add
datatype is the data type of the column you want to add (for example: varchar or int)
you can read more here: https://www.w3schools.com/ sql/sql_alter.asp

sql.execute(f'ALTER TABLE {table_name} ADD {column_name} {datatype}')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question