K. ossama
K. ossama

Reputation: 433

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!

Upvotes: 0

Views: 94

Answers (2)

boardrider
boardrider

Reputation: 6185

You can emulate a database with Python objects.

Create a dict, and store all your data therein.

Then, serialise (pickle) the data to disk (with pickle.dump) and next time you need to access/manipulate the data, use pickle.load.

Upvotes: 0

Abhishek Kedia
Abhishek Kedia

Reputation: 899

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.

Upvotes: 1

Related Questions