PMYSQL
PMYSQL
PMYSQL
Create Connection ꞉
Start by creating a connection to the database.
In [3]: mydb=mysql.connector.connect(host="localhost",user='root',password='Kanha@8144')
print(mydb)
Creating Cursor
The MySQLCursor of mysql-connector-python (and similar libraries) is
used to execute statements to communicate with the MySQL database. Using
the methods of it you can execute SQL statements, fetch data from the
result sets, call procedures.
In [4]: cursor=mydb.cursor()
Now you can start querying the database using SQL statements.
Creating Database
To create a database in MySQL, use the "CREATE DATABASE" statement:
If the above code was executed with no errors, you have successfully created a database.
cursor.fetchall()
[('cardataset',),
Out[47]:
('information_schema',),
('mydatabase',),
('mysql',),
('performance_schema',),
('practicedb',),
('students',),
('students1',),
('sys',)]
Creating Table
To create a table in MySQL, use the "CREATE TABLE" statement.
Make sure you define the name of the database when you create the table
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="Kanha@8144",
database="mydatabase"
)
cursor = mydb.cursor()
cursor.execute("SHOW TABLES")
cursor.fetchall()
Primary Key
When creating a table, you should also create a column with a unique key
for each record.
We use the statement "INT AUTO_INCREMENT PRIMARY KEY" which will insert
a unique number for each record. Starting at 1, and increased by one for
each record.
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="Kanha@8144",
database="mydatabase"
)
cursor = mydb.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS customers (id INT AUTO_INCREMENT PRIMARY KEY,
cursor.execute(query,val)
Important!꞉ Notice the statement꞉ mydb.commit(). It is required to make the changes, otherwise
no changes are made to the table.
In [16]: query = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = [
('Peter', 'Lowstreet 4'),
('Amy', 'Apple st 652'),
('Hannah', 'Mountain 21'),
('Michael', 'Valley 345'),
('Sandy', 'Ocean blvd 2'),
('Betty', 'Green Grass 1'),
('Richard', 'Sky st 331'),
('Susan', 'One way 98'),
('Vicky', 'Yellow Garden 2'),
('Ben', 'Park Lane 38'),
('William', 'Central st 954'),
('Chuck', 'Main Road 989'),
('Viola', 'Sideway 1633')
]
cursor.executemany(query, val)
mydb.commit()
13 rows inserted.
Get Inserted ID
You can get the id of the row you just inserted by asking the cursor
object.
Note꞉ If you insert more than one row, the id of the last inserted row is returned.
In [24]: # List of tuples with values for multiple rows
values = [
('Alice', '123 Main St'),
('Bob', '456 Elm St'),
('Charlie', '789 Oak St')
]
cursor.executemany(query, values)
Note꞉ We use the fetchall() method, which fetches all rows from the last executed statement.
Selecting Columns
To select only some of the columns in a table, use the "SELECT"
statement followed by the column name(s):
The fetchone() method will return the first row of the result:
In [36]: cursor.fetchmany()
In [39]: cursor.fetchmany(5)
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="Kanha@8144",
database="mydatabase"
)
cursor = mydb.cursor()
query= "SELECT * FROM customers WHERE address ='Park Lane 38'"
cursor.execute(query)
cursor.fetchall()
Wildcard Characters
You can also select the records that starts, includes, or ends with a
given letter or phrase.
cursor.execute(sql)
cursor.fetchall()
In [46]: sql = "SELECT * FROM customers WHERE address LIKE 'Green%' "
cursor.execute(sql)
cursor.fetchall()
In [47]: sql = "SELECT * FROM customers WHERE address LIKE '%Garden 2'"
cursor.execute(sql)
cursor.fetchall()
cursor.execute(sql)
cursor.fetchall()
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="Kanha@8144",
database="mydatabase"
)
cursor = mydb.cursor()
cursor.execute(sql, adr)
cursor.fetchall()
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="Kanha@8144",
database="mydatabase"
)
cursor = mydb.cursor()
cursor.execute(sql, adr)
cursor.fetchall()
The ORDER BY keyword sorts the result ascending by default. To sort the
result in descending order, use the DESC keyword.
ORDER BY DESC
Use the DESC keyword to sort the result in a descending order.
cursor.execute(sql)
cursor.fetchall()
Update Table
You can update existing records in a table by using the "UPDATE" statement꞉
In [20]: sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 345'"
cursor.execute(sql)
mydb.commit()
1 record(s) affected
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="Kanha@8144",
database="mydatabase"
)
cursor = mydb.cursor()
mydb.commit()
1 record(s) affected
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="Kanha@8144",
database="mydatabase"
)
cursor=mydb.cursor()
cursor.fetchall()
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="Kanha@8144",
database="mydatabase"
)
cursor=mydb.cursor()
cursor.fetchall()
Assuming you want to create two tables, employees and departments, and
associate them through a department ID:
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="Kanha@8144",
database="mydatabase"
)
cursor=mydb.cursor()
In [27]: query="CREATE TABLE employees (id INT AUTO_INCREMENT PRIMARY KEY,name VARCHAR(255) NOT N
cursor.execute(query)
query = "INSERT INTO employees (name, department_id, salary, hire_date) VALUES (%s, %s,
cursor.executemany(query, employee_data)
mydb.commit()
1.Inner Join
In [40]: import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="Kanha@8144",
database="mydatabase"
)
cursor=mydb.cursor()
cursor.execute(query)
result = cursor.fetchall()
2.Left Join
In [41]: # LEFT JOIN example
query = """
SELECT employees.name, departments.department_name
FROM employees
LEFT JOIN departments ON employees.department_id = departments.id
"""
cursor.execute(query)
result = cursor.fetchall()
print("\nLEFT JOIN꞉")
for row in result꞉
print(row)
LEFT JOIN꞉
('John Doe', 'HR')
('Jane Smith', 'IT')
('Bob Johnson', 'HR')
('Alice Brown', 'Sales')
3.Right Join
In [42]: # RIGHT JOIN example
query = """
SELECT employees.name, departments.department_name
FROM employees
RIGHT JOIN departments ON employees.department_id = departments.id
"""
cursor.execute(query)
result = cursor.fetchall()
print("\nRIGHT JOIN꞉")
for row in result꞉
print(row)
RIGHT JOIN꞉
('Bob Johnson', 'HR')
('John Doe', 'HR')
('Jane Smith', 'IT')
('Alice Brown', 'Sales')
3. Full Join
In [43]: # FULL JOIN emulation using UNION of LEFT JOIN and RIGHT JOIN
query = """
SELECT employees.name, departments.department_name
FROM employees
LEFT JOIN departments ON employees.department_id = departments.id
UNION
SELECT employees.name, departments.department_name
FROM employees
RIGHT JOIN departments ON employees.department_id = departments.id
"""
cursor.execute(query)
result = cursor.fetchall()
In [ ]:
Delete Record
You can delete records from an existing table by using the "DELETE FROM"
statement:
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="Kanha@8144",
database="mydatabase"
)
cursor=mydb.cursor()
sql = "DELETE FROM customers WHERE address = 'Mountain 21'"
cursor.execute(sql)
mydb.commit()
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="Kanha@8144",
database="mydatabase"
)
cursor = mydb.cursor()
Important!꞉ Notice the statement꞉ mydb.commit(). It is required to make the changes, otherwise no
changes are made to the table.
WHERE clause in the DELETE syntax꞉ The WHERE clause specifies which record(s) that should be
deleted. If you omit the WHERE clause, all records will be deleted!
cursor.execute(sql, adr)
mydb.commit()
1 record(s) deleted
Delete a Table
You can delete an existing table by using the "DROP TABLE" statement:
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="Kanha@8144",
database="mydatabase"
)
cursor = mydb.cursor()
query="DROP TABLE customers"
cursor.execute(query)
‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
MySQLInterfaceError Traceback (most recent call last)
File ~/anaconda3/lib/python3.11/site‑packages/mysql/connector/connection_cext.py꞉639, in
CMySQLConnection.cmd_query(self, query, raw, buffered, raw_as_string)
638 query = query.encode("utf‑8")
‑‑> 639 self._cmysql.query(
640 query,
641 raw=raw,
642 buffered=buffered,
643 raw_as_string=raw_as_string,
644 query_attrs=self.query_attrs,
645 )
646 except MySQLInterfaceError as err꞉
The above exception was the direct cause of the following exception꞉
File ~/anaconda3/lib/python3.11/site‑packages/mysql/connector/opentelemetry/context_prop
agation.py꞉77, in with_context_propagation.<locals>.wrapper(cnx, *args, **kwargs)
75 """Context propagation decorator."""
76 if not OTEL_ENABLED or not cnx.otel_context_propagation꞉
‑‑‑> 77 return method(cnx, *args, **kwargs)
79 current_span = trace.get_current_span()
80 tp_header = None
File ~/anaconda3/lib/python3.11/site‑packages/mysql/connector/connection_cext.py꞉647, in
CMySQLConnection.cmd_query(self, query, raw, buffered, raw_as_string)
639 self._cmysql.query(
640 query,
641 raw=raw,
(...)
644 query_attrs=self.query_attrs,
645 )
646 except MySQLInterfaceError as err꞉
‑‑> 647 raise get_mysql_exception(
648 err.errno, msg=err.msg, sqlstate=err.sqlstate
649 ) from err
650 except AttributeError as err꞉
651 addr = (
652 self._unix_socket if self._unix_socket else f"{self._host}꞉{self._port}"
653 )
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="Kanha@8144",
database="mydatabase"
)
cursor=mydb.cursor()
cursor.execute("SHOW TABLES")
cursor.fetchall()
[]
Out[2]:
[('cardataset',),
Out[3]:
('information_schema',),
('mydatabase',),
('mysql',),
('performance_schema',),
('practicedb',),
('students',),
('students1',),
('sys',)]
In [ ]:
In [ ]: