Question

I've created a database using my sql/python programming knowledge. However, I wanted to know how I would be able to clear all data in a given column.

The code I tried to use is below:

#Creating the Table
import sqlite3 as lite
import sys

con = lite.connect('Test.db')

with con:

    cur = con.cursor()    
    cur.execute('SELECT SQLITE_VERSION()')

    data = cur.fetchone()

    print("SQLite version: %s" % data)

#Adding data
with con:
    cur = con.cursor()    
    cur.execute("CREATE TABLE Users(User_Id INTEGER PRIMARY KEY, Username STRING, Password STRING, Acc_Type STRING, First_Name STRING, Surname STRING, Class STRING, FullName STRING)")
    cur.execute("INSERT INTO Users VALUES(1, 'Admin', 'PassWord567', 'Admin', '', 'Admin', 'None', 'Admin')")
    cur.execute("INSERT INTO Users VALUES(2, 'HamzahA12', 'password', 'Student', 'Hamzah', 'Akhtar', '13E2', 'Hamzah Akhtar')")
#Clearing a Column
column_length = []
with con:
    cur = con.cursor()
    cur.execute("SELECT Username FROM Users")
    rows = cur.fetchall()
    for row in rows:
        row = str(row)
        column_length.append(row)
length = 1
for item in column_length:
    length = str(length)
    with con:
        cur = con.cursor()
        cur.execute("DELETE FROM Users WHERE User_Id = '"+length+"'")
    length = int(length)
    length = length+1

When i run the code, it clears the table rather than the column. I understand why it does that but i cant find a way around it?!

Was it helpful?

Solution

You don't need the two loops; you can change all column values with a single statement:

con.cursor().execute("UPDATE Users SET Username = NULL")

OTHER TIPS

You need to change the line:

cur.execute("UPDATE Users SET YourColumn=null WHERE User_Id = '"+length+"'")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top