0

I am trying to create a database with SQLite3 in Python.

Creating a table appears to work, but whenever I try to insert data, it doesn't seem to add anything to the database as fetchall() returns nothing, However, if I try to create the ID again, it complains about unique constraint failed.

Initialization:

import sqlite3
conn = sqlite3.connect('login.db')
c = conn.cursor()

Table Creation:

c.execute("""CREATE TABLE Login (ID INTEGER PRIMARY KEY,
First TEXT NOT NULL,
Last TEXT NOT NULL,
Middle TEXT NOT NULL,
Gender TEXT NOT NULL);""")
conn.commit()

Data Insert:

c.execute("""INSERT INTO Login VALUES (6, 'First', 'Last', 'Hello', 'Male');""")
conn.commit()

Fetching Tables:

print(c.fetchall())

c.close()
conn.close()

When dropping the table into an online reader, it also appears empty.

EDIT: This is what is shown in the db reader, and in google sheets, large list of blanks / ";" then this enter image description here

2
  • Try to specify columns in your INSERT statement. Commented Jan 30, 2021 at 20:35
  • I did, it did nothing Commented Jan 30, 2021 at 20:36

1 Answer 1

1

c.fetchall() would return all of the rows from a SELECT query, which you aren't doing.

import sqlite3
conn = sqlite3.connect('login.db')
c = conn.cursor()
c.execute("""CREATE TABLE Login (ID INTEGER PRIMARY KEY, First TEXT NOT NULL, Last TEXT NOT NULL, Middle TEXT NOT NULL, Gender TEXT NOT NULL);""")
conn.commit()
c.execute("""INSERT INTO Login VALUES (6, 'First', 'Last', 'Hello', 'Male');""")
conn.commit()
c.execute("SELECT * FROM login")
print(c.fetchall())

will happily print

[(6, 'First', 'Last', 'Hello', 'Male')]

As an aside, your code is vulnerable to SQL injection attacks, and you should do

import sqlite3

conn = sqlite3.connect("login.db")
c = conn.cursor()
c.execute(
    """CREATE TABLE Login (ID INTEGER PRIMARY KEY, First TEXT NOT NULL, Last TEXT NOT NULL, Middle TEXT NOT NULL, Gender TEXT NOT NULL);"""
)
conn.commit()
c.execute(
    "INSERT INTO Login (ID, First, Last, Middle, Gender) VALUES (?,?,?,?,?)",
    (6, "First", "Last", "Hello", "Male"),
)
conn.commit()
c.execute("SELECT * FROM login")
print(c.fetchall())
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your help.
A few hours later I know but I looked into the SQL injection vulnerability part and it does seem like a big problem! This isn't production code but I didn't know about this vulnerability, thanks for pointing it out.
Even so, you would have bumped into the issue the first time you attempted to insert anything with quote characters :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.