My SQL Connectivity
My SQL Connectivity
MySQL connectivity
Why python ?
Programming in python is arguably more efficient and faster as compared
to other languages.
Closed and open connection of the database are taken care of by python
without the action from developer side.
Installing mysql-connector-python
pip install mysql-connector-python
OR
python -m install mysql-connector
Establishing connection
MySQL connectivity 1
import mysql.connector as x #importing with an alias of x
MySQL connectivity 2
Cursors are created using the connection.cursor() method
They are tied to the connection that created them for their entire existence
All database commands executed through the cursor operate within the
context of the database session associated with the connection
In simpler terms, a cursor is like a tool that allows your Python program to
interact with the MySQL database. It's created from your connection to the
database and remains linked to that connection. When you use the cursor to
run commands or queries, these actions take place within the specific database
session you're connected to.
import mysql.connector
conn=x.connect(host="localhost",user="root",password="<your_pa
# Create cursor
cursor = conn.cursor()
# Execute an INSERT statement
cursor.execute("INSERT INTO employees (name, age) VALUES ('Jo
# Get the number of rows affected
rows_affected = cursor.rowcount
#this returns a value of 1 as only one row was inserted.
print(f"Number of rows inserted: {rows_affected}")
conn.commit()
MySQL connectivity 3
cursor.close()
conn.close()
In this example, after executing the INSERT statement, cursor.rowcount will return
2, as two rows were inserted into the 'employees' table.
import mysql.connector
conn = mysql.connector.connect(user='user', password='passw
ord', host='localhost', database='test')
cursor = conn.cursor()
cursor.execute("INSERT INTO employees (name) VALUES ('Joh
n')")
conn.commit() # Commits the change
MySQL connectivity 4
cursor.execute("SELECT * FROM employees")
row = cursor.fetchone() # Fetches one row
print(row)
fetchall() : Retrieves all rows from the result set and returns a list of tuples.
If some rows have been already extracted from the result set, then it
retrieves the remaining rows from result set.
fetchmany(size) : Retrieves the specified number of rows from the result set
as a list of tuples. The default size is 1; if there are no rows in the result set,
[] is returned.
MySQL connectivity 5