Unit 5 Python
Unit 5 Python
Python being a high-level language provides support for various databases. We can connect
and run queries for a particular database using Python and without writing raw queries in the
terminal or shell of that particular database, we just need to have that database installed in
our system.
Python MySQL
Python MySQL Connector is a Python driver that helps to integrate Python and MySQL.
This Python MySQL library allows the conversion between Python and MySQL data types.
MySQL Connector API is implemented using pure Python and does not require any third-
party library.
How to install MySQL connector package in Python?
A connector is employed when we have to use MySQL with other programming languages.
The work of mysql-connector is to provide access to MySQL Driver to the required
language. Thus, it generates a connection between the programming language and the
MySQL Server.
To install Python-mysql-connector module, one must have Python and PIP(Preferred
Installer Program), preinstalled on their system.
*PIP is a package management system used to install and manage software
packages/libraries written in Python. These files are stored in a large “on-line repository”
termed as Python Package Index (PyPI).
mysql-connector method can be installed on Windows with the use of following command:
pip install mysql-connector-python
Also, to uninstall current MySQL Connector/Python, you use the following command:
pip uninstall mysql-connector-python
Connecting to the Database
The mysql.connector provides the connect() method used to create a connection between the
MySQL database and the Python application. The syntax is given below.
Syntax:
Conn_obj= mysql.connector.connect(host = <hostname>, user = <username>, passwd
= <password>)
The connect() function accepts the following arguments.
Hostname – It represents the server name or IP address on which MySQL is running.
Username – It represents the name of the user that we use to work with the MySQL server.
By default, the username for the MySQL database is root.
Password – The password is provided at the time of installing the MySQL database. We
don’t need to pass a password if we are using the root.
Database – It specifies the database name which we want to connect. This argument is used
when we have multiple databases.
EXAMPLE:
import mysql.connector
print(conn)
Output:
Also for the same, we can use connection.MySQLConnection() class instead of connect():
from mysql.connector import connection
print(conn)
Another way is to pass the dictionary in the connect() function using ‘**’ operator:
from mysql.connector import connection
dict = {
'user': 'root',
'host': 'localhost',
'database': 'College'
}
print(conn)
CREATING DATABASE
# Python implementation to create a Database in MySQL
import mysql.connector
# cursor object c
c = db.cursor()
What is cursor?
In the context of databases and MySQL, a cursor is an object used to interact with the
database. It acts as a pointer to the result set of a query, allowing you to execute SQL
statements, fetch data, and manage transactions within the database.
CREATING TABLE
Now in order to create the table, we use the create table command. It is recommended to
always keep a primary key
CREATE TABLE
(
column1 column1_data_type,
column2 column2_data_type,
column3 column3_data_type...
);
# Python implementation to create a table in MySQL
import mysql.connector
# cursor object c
c = db.cursor()
c.execute(employeetbl_create)
INSERTING DATA
Inserting the data into tables is a crucial part, it is required to make sure there is no mismatch
of data i.e. the data type being sent should match the data type of the particular column.
The general syntax for insert statements:
INSERT INTO <TABLE_NAME> (column1,column2,column3...) VALUES
(data1,data2,data3...);
# Python implementation to insert data into a table in MySQL
import mysql.connector
db = mysql.connector.connect(
host="localhost",
user="root",
passwd="password",
database="employee_db"
)
# cursor object c
c = db.cursor()
# execute the insert commands for all rows and commit to the database
c.executemany(employeetbl_insert, data)
db.commit()
db = mysql.connector.connect(
host="localhost",
user="root",
passwd="password",
database="employee_db"
)
# cursor object c
c = db.cursor()
db = mysql.connector.connect(
host="localhost",
user="root",
passwd="password",
database="employee_db"
)
# cursor object c
c = db.cursor()
DELETING DATA
Deleting data from tables has to be done with utmost care as it can lead to the loss of
important data at times.
DELETE FROM <TABLE_NAME> WHERE <PRIMARY KEY NAME> = <PRIMARY KEY VALUE>
import mysql.connector
db = mysql.connector.connect(
host="localhost",
user="root",
passwd="password",
database="employee_db"
)
# cursor object c
c = db.cursor()
DELETING DATABASE
import mysql.connector
To connect python with MongoDB we must have Mongo in our system and install pymongo
library. pymongo library, which serves as the official Python driver for MongoDB
pip install pymongo
Method2 :
mydatabase = client.name_of_the_database
print(db.name)
Accessing the Collection : Collections are equivalent to Tables in RDBMS. We access a
collection in PyMongo in the same way as we access the Tables in the RDBMS.
Method 1:
mycollection = mydatabase[‘myTable’]
Method 2 :
mycollection = mydatabase.myTable
client = MongoClient("mongodb://localhost:27017/")
# Access a database
db = client["mydatabase"]
collection = db["mycollection"]
docs = [
collection.insert_many(docs)
try:
conn = MongoClient("mongodb://localhost:27017/")
print("Connected successfully!!!")
except:
print("Could not connect to MongoDB")
Querying in MongoDB
There are certain query functions which are used to filter the data in the database. The two
most commonly used functions are:
1. find(): find() is used to get more than one single document as a result of query.
# Find all documents with a specific filter
print(doc)
all_docs = collection.find()
print(doc)
2. count(): count() is used to get the numbers of documents with the name as passed in
the parameters.
print(mydatabase.myTable.count({title: 'MongoDB and Python'}))
3. find_one(): find_one() retrieves the first document that matches the specified filter
criteria. If no criteria are specified, it returns the first document in the collection.
# Import the MongoClient
client = MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["mycollection"]
print(result)
result = collection.find_one()
print(result)
limited_docs = collection.find().limit(2)
print(doc)
Comparison Operators
MongoDB provides various comparison operators to filter results, such as $gt, $lt, $gte,
$lte, $ne, and $in.
# Find documents where age is greater than 20
results = collection.find(query)
Logical Operators
Logical operators like $and, $or, and $not allow combining multiple conditions.
# Find documents where age > 20 and city is 'New York'
results = collection.find(query)
results = collection.find(query)
Updating Data
MongoDB updates are done with update_one() (for a single document) or update_many()
(for multiple documents). Both methods require two arguments:
A filter specifying the documents to update.
An update operation (e.g., $set, $inc) defining the changes
1. update_one()
Updates the first document that matches the filter criteria.
from pymongo import MongoClient
# Connect to the MongoDB server
client = MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["mycollection"]
# Update one document - sets the 'age' field to 26 for the document with name 'Alice'
2. update_many()
Updates all documents that match the filter criteria.
# Update multiple documents - sets the 'city' field to 'LA' for all documents with
'city': 'Los Angeles'
*If update_one() or update_many() does not find any document that matches the filter,
MongoDB will not throw an error or make any changes. To check whether the valued
matched or not we can perform following operation:
# Try updating a non-existent document
Deleting Data
For deletions, MongoDB provides delete_one() and delete_many(), which take a filter
specifying the documents to delete.
1. delete_one()
Deletes the first document that matches the filter criteria.
# Delete one document with the name 'Charlie'
collection.delete_one({"name": "Charlie"})
2. delete_many()
Deletes all documents that match the filter criteria.
# Delete all documents with 'city': 'LA'
collection.delete_many({"city": "LA"})
collection.delete_many({})
*if delete_one() or delete_many() does not find any document matching the filter criteria,
MongoDB does nothing.
# Try deleting a non-existent document