Insert
The way we add in data to our table is INSERT. If we use INSERT INTO followed by the table name, then VALUES and the actual values we are able to add our values into the table. For example, to add data where the name is Tom and the grade is 90, we would do the following:
#You can insert into a SQL database with INSERT INTO followed by the table and values
#Notice the quotes around Tom because it is a character
query = """INSERT INTO students
VALUES ("Tom",90);"""
cur.execute(query)
If you insert without values for all the columns, the columns after the ones you supply data for will be left as null.
#You can insert into a SQL database with INSERT INTO followed by the table and values
#Notice the quotes around Tom because it is a character
query = """INSERT INTO students
VALUES ("Tom",90);"""
cur.execute(query)
You can specify what columns to be added to specifically by giving both the column names following the table name then inserting the values as usual. The following will add just the value Josh to the name column.
#You can also selectively insert into only certain columns
query = """INSERT INTO students (name)
VALUES ("Josh");"""
cur.execute(query)
If you want to insert multiple rows at a time, it can be achieved by following the first set of values enclosed in parantheses with another set.
#You can also insert multiple rows at the same time
query = """INSERT INTO students
VALUES ("Mary",85),("Clair",95);"""
cur.execute(query)
We’ve done all these updates but we need to also commit the changes to save.
#Use commit() to save your changes
conn.commit()
We can close the connection by calling conn.close()
#Then close the connection with close()
conn.close()