K. ossama K. ossama - 3 months ago 8
Python Question

how to connect an app to a database with python?

I'm new to python, so I want to know how to store the data in a database!

For a sample example, I want to store informations about users :

ent1 = input('Enter your name: ')
ent2 = input('Enter your adress: ')
ent3 = int(input('Enter your number phone: '))


The question is how to connect the input with the database?

we can take the example of the sqlite3 that is preinstalled in python! and we suppose that we have a database called user.db connected to the cursur and a table called users that contains three columns (name, adress, number_phone)

thanks for the help!

Answer

Use sqllite3 library to perform SQL insert query to insert data into database. For example

import sqlite3
conn = sqlite3.connect('user.db')

## Create table. Skip if table already exists
conn.execute('''CREATE TABLE IF NOT EXISTS users
       (name    TEXT NOT NULL,
       adress   TEXT,
       number_phone TEXT);''')

ent1 = input('Enter your name: ')
ent2 = input('Enter your adress: ')
ent3 = int(input('Enter your number phone: '))

#Insert into users table
conn.execute("INSERT INTO users (name,adress,number_phone) \
      VALUES (?,?,?)",[ent1,ent2,ent3]);
conn.commit() #don't forget commit to save data
conn.close()

You can also have a look at the official documentation for detailed info and API references.