Python SQLite Insert Into

by Atakan

Hello, I will talk about database operations on entering data into the table.
We will look at the use of the widely used INSERT INTO statement.

First, we import the sqlite3 package as standard

import sqlite3

Then we get the connection object and the cursor object.

conn = sqlite3.connect("contact_list.db")
cursor = conn.cursor()

I think our table is already set up.if not you can check my previous post about how it was created. Python SQLite Create Table

I wrote the method that will perform INSERT INTO operation as follows.
Here the 1st parameter comes to my id field.This is an Auto Increment primary key field , so I’m going to send None type here , this causes this; automatically and uniquely assign the next id value.

def save_my_contact(name, number, city, alias):
    query = "INSERT INTO contact_table VALUES (?,?,?,?,?)"
    params = (None, name, number, city, alias)
    cursor.execute(query, params)
    conn.commit()

full code of

insert_into.py
import sqlite3

conn = None
cursor = None


def init_connections():
    global conn
    global cursor
    conn = sqlite3.connect("contact_list.db")
    cursor = conn.cursor()

def close_connecton():
    cursor.close()
    conn.close()


def save_my_contact(name, number, city, alias):
    query = "INSERT INTO contact_table VALUES (?,?,?,?,?)"
    params = (None, name, number, city, alias)
    cursor.execute(query, params)
    conn.commit()


init_connections()
save_my_contact("Atakan","012345678","Munich","Atakan")
close_connecton()

Result of DB Browser for SQLite

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. OK Read More