Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Working with Databases (SQL and NoSQL)

Working with Databases (SQL and NoSQL)

Working with databases is a crucial part of many applications. There are two main types of databases: SQL (relational) databases and NoSQL databases. Here's an overview of how to work with both types using Python:

SQL Databases:

SQL databases are structured databases that use structured query language (SQL) to manage and manipulate data. Some popular SQL databases are MySQL, PostgreSQL, SQLite, and Microsoft SQL Server.

1. Connecting to an SQL Database:

You can use libraries like sqlite3 for SQLite, psycopg2 for PostgreSQL, and mysql-connector for MySQL to connect to SQL databases. Here's an example using SQLite:

import sqlite3

# Connect to the database
conn = sqlite3.connect('mydatabase.db')
cursor = conn.cursor()
     

 

 

2. Creating Tables:

You define the structure of your data using SQL statements to create tables.

create_table_query = '''
CREATE TABLE users (
id INTEGER PRIMARY KEY,
username TEXT,
email TEXT
)
'''

cursor.execute(create_table_query)
conn.commit()
   

 

 

3. Inserting Data:

insert_data_query = '''
INSERT INTO users (username, email) VALUES (?, ?)
'''

data = ('john_doe', 'john@example.com')
cursor.execute(insert_data_query, data)
conn.commit()
     

 

 

4. Retrieving Data:

select_query = '''
SELECT * FROM users
'''

cursor.execute(select_query)
data = cursor.fetchall()
print(data)
     

 

 

NoSQL Databases:

NoSQL databases are non-relational databases that offer flexibility and scalability. Types of NoSQL databases include document-based (e.g., MongoDB), key-value (e.g., Redis), and column-family (e.g., Cassandra) databases.

1. Connecting to a NoSQL Database:

You'll need to install the appropriate library for your chosen NoSQL database. For MongoDB, you can use pymongo.

from pymongo import MongoClient

# Connect to the MongoDB server
client = MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
       

 

 

2. Inserting Data:

user_data = {
'username': 'john_doe',
'email': 'john@example.com'
}

users_collection = db['users']
users_collection.insert_one(user_data)
   

 

 

3. Querying Data:

user = users_collection.find_one({'username': 'john_doe'})
print(user)
   

 

 

4. Updating Data:

users_collection.update_one(
{'username': 'john_doe'},
{'$set': {'email': 'newemail@example.com'}}
)
   

 

 

Both SQL and NoSQL databases have their strengths and are suitable for different types of applications. Your choice depends on factors like data structure, querying requirements, scalability, and your familiarity with the database type.