简体   繁体   中英

sqlite3 | data doesn't save in table

The code works when I run it but when I run it again the data from the previous run is not saved, but the table is still there. I have tried many methods of saving the file and it still doesn't save

import sqlite3

conn = sqlite3.connect('conntact.db')
cursor = conn.cursor()
check = cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='contacts'");


if check == 0:
    cursor.execute('''CREATE TABLE contacts
       (ID INTEGER PRIMARY KEY AUTOINCREMENT,
        NAME            TEXT    NOT NULL,
        EMAIL           TEXT    NOT NULL,
        PHONE           TEXT    NOT NULL);''');

def add_contacts():
    name1 = input("Enter contact name: ")
    email1 = input("Enter contact email: ")
    phone1 = input("Enter contact phone number: ")
    id_s = input("Enter id: ")
    cursor.execute("INSERT INTO contacts (ID, NAME,EMAIL,PHONE) VALUES (?,?,?,?)", (id_s, name1, email1, phone1));



def read_all_contact():
    cursor.execute("SELECT * FROM contacts");
    records = cursor.fetchall()
    print(f"Total rows are: {len(records)}")
    for row in records:
        print(f'ID: {row[0]}')
        print(f'Name: {row[1]}')
        print(f'Email: {row[2]}')
        print(f'Phone: {row[3]}\n')
        
    

add_contacts()
read_all_contact()
conn.close()

Any help would a apreciated

  1. Remove check =... line, which is wrong anyway.
  2. Remove if check == 0
  3. Replace "CREATE TABLE contacts" with "CREATE TABLE IF NOT EXISTS contacts"
  4. Execute conn.commit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM