Hi so I'm a beginner who just created a simple code (it's only for a test actually) on connecting python file to db file for SQL. Here is my code:
import sqlite3
connection = sqlite3.connect('aquarium.db')
cursor = connection.cursor()
cursor.execute("""CREATE TABLE fish (
name TEXT,
species TEXT,
tank_number INTEGER)
""")
cursor.execute("INSERT INTO fish VALUES ('Wharton', 'shark', 1)")
cursor.execute("INSERT INTO fish VALUES ('Crimson', 'cuttlefish', 7)")
rows = cursor.execute("SELECT name, species, tank_number FROM fish").fetchall()
print(rows)
The thing is, when I opened aquarium.db with DB browser, only the table is created, but the values from my INSERT INTO isn't being inserted. Is there anything that I did wrong? Picture of my DB Browser
I use VSCode to code by the way. I've also put the db file in the same location as my py file. and I am using MAC
CodePudding user response:
You don't have to create a table with same name.
import sqlite3
connection = sqlite3.connect('aquarium.db')
print(connection)
cursor = connection.cursor()
print(cursor)
cursor.execute("""CREATE TABLE fish (
name TEXT,
species TEXT,
tank_number INTEGER)
""")
cursor.execute("INSERT INTO fish VALUES ('Wharton', 'shark', 1)")
cursor.execute("INSERT INTO fish VALUES ('Crimson', 'cuttlefish', 7)")
rows = cursor.execute("SELECT name, species, tank_number FROM fish").fetchall()
print(rows)
Can you comment the out put of that block.
CodePudding user response:
import sqlite3
connection = sqlite3.connect('aquarium.db')
cursor = connection.cursor()
cursor.execute("""CREATE TABLE fish (
name TEXT,
species TEXT,
tank_number INTEGER)
""")
cursor.execute("INSERT INTO fish (name, species, tank_number) VALUES ('Wharton', 'shark', 1)")
cursor.execute("INSERT INTO fish VALUES ('Crimson', 'cuttlefish', 7)")
rows = cursor.execute("SELECT name, species, tank_number FROM fish").fetchall()
connection.commit()