You are on page 1of 28

PYTHON AND MYSQL

 DFN40263 - PROGRAMMING ESSENTIALS IN PYTHON


LO
• Prepare MySQL database for Python
• Prepare connection between Python with MySQL
a. Arrange connection using “MySQL Connector” driver (e.g.:
PIP)
b. Prepare MySQL database
c. Arrange MySQL table
d. Prepare to drop MySQL table
Python PIP
• What is PIP?
• PIP is a package manager for Python packages, or modules if you
like.
• Note: If you have Python version 3.4 or later, PIP is included by
default.
• What is a Package?
• A package contains all the files you need for a module.
• Modules are Python code libraries you can include in your project.
Check PIP Version
• Check if PIP is Installed
• Navigate your command line to the location of Python's script directory, and
type the following
Python PIP
• Download a Package
• Downloading a package is very easy.
• Open the command line interface and tell PIP to download the package you
want.
• Navigate your command line to the location of Python's script directory, and
type the following: pip install camelcase
Python PIP
• Using installed Package
• Once the package is installed, it is ready to use.
• Import the "camelcase" package into your project.

import camelcase
c = camelcase.CamelCase()
txt = "hello world"
print(c.hump(txt))
Remove a Package
• Use the uninstall command to remove a package:
• Example
• Uninstall the package named "camelcase":

• The PIP Package Manager will ask you to confirm that you want to remove the camelcase
package:

• Would remove:
• Press y and the package will be removed.
Python PIP
• List Packages
• Use the list command to list all the packages installed on your system
Python MySQL
• Python can be used in database applications.
• One of the most popular databases is MySQL.
• Install MySQL Driver
• Python needs a MySQL driver to access the MySQL database.
• We will use the driver "MySQL Connector".
• Install "MySQL Connector“ through PIP.
• PIP is most likely already installed in your Python environment.
• Navigate your command line to the location of PIP, and type the following:
python -m pip install mysql-connector-python
Python MySQL
• Test MySQL Connector
• To test if the installation was successful, or if you already have
"MySQL Connector" installed, create a Python page with the following
content:
import mysql.connector
• If the above code was executed with no errors, "MySQL Connector" is
installed and ready to be used.
Create Connection
• Start by creating a connection to the database.
• Use the username and password from your MySQL database:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  password=""
)

print(mydb)
Creating a Database
• To create a database in MySQL, use the "CREATE DATABASE" statement:
• Example
• create a database named "dbContoh":
import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  password=""
)

mycursor = mydb.cursor()

mycursor.execute("CREATE DATABASE dbContoh")


Check if Database Exists
• You can check if a database exist by listing all databases in your system by using the "SHOW DATABASES"
statement:
• Example
• Return a list of your system's databases:
import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword"
)

mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor:
  print(x)
Connecting to Database
import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  password="",
  database="dbContoh"
)
Python MySQL Create Table
import mysql.connector
• To create a table in dataBase = mysql.connector.connect(
host = "localhost",
MySQL, use the "CREATE user = "root",
passwd = "",
TABLE" statement. database = "dbContoh" )
cursorObj = dataBase.cursor()
• Make sure you define the studentRecord = """CREATE TABLE STUDENT (
NAME VARCHAR(20) NOT NULL,
name of the database COURSE VARCHAR(50),
DEPT VARCHAR(50),
when you create the MATRICNO VARCHAR(12) NOT NULL,
connection AGE INT
)"""
cursorObj.execute(studentRecord)
dataBase.close()
Python MySQL – Drop Table
• You can delete an existing table by using the "DROP TABLE"
statement:
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="dbContoh"
)

mycursor = mydb.cursor()
sql = "DROP TABLE STUDENT"
mycursor.execute(sql)
LO
• Manipulate MySQL database for Python
• Manipulate MySQL database using Python program
• Insert multiple row into table
• Update data
• Delete row
• Display data from query
Python MySQL Insert Into Table
import mysql.connector To fill a table in MySQL, use the "INSERT INTO" statement.
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="dbContoh"
)
mycursor = mydb.cursor()
sql = "INSERT INTO student (name,course,dept,matricno) VALUES (%s, %s, %s, %s)"
val = ("Muhammad Haziq Zafran B Mohd Khairi", "DDT","JTMK","01DDT21F1001")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
Argument Specifiers
• Here are some basic argument specifiers you should know:
• %s - String (or any object with a string representation, like numbers)
• %d - Integers
• %f - Floating point numbers
• %.<number of digits>f - Floating point numbers with a fixed amount of digits
to the right of the dot.
• %x/%X - Integers in hex representation (lowercase/uppercase)
Insert Multiple Rows To insert multiple rows into a table, use the
executemany() method.

The second parameter of the executemany()


method is a list of tuples, containing the data
you want to insert:
Python MySQL Update Table
You can update existing records in a table by using the
"UPDATE" statement:

Important!: Notice the statement:


mydb.commit(). It is required to
make the changes, otherwise no
changes are made to the table.

Notice the WHERE clause in the UPDATE syntax: The WHERE


clause specifies which record or records that should be
updated. If you omit the WHERE clause, all records will be
updated!
Prevent SQL Injection
• It is considered a good practice to escape the values of any query, also
in update statements.
• This is to prevent SQL injections, which is a common web hacking
technique to destroy or misuse your database.
• The mysql.connector module uses the placeholder %s to escape
values in the update statement
Prevent SQL Injection
Python MySQL Delete From By
You can delete records from an existing table by
using the "DELETE FROM" statement:
Python MySQL Select From
To select from a table in MySQL, use the "SELECT" statement:

Note: fetchall() method is use to fetches all rows from the last executed statement.

You might also like