Professional Documents
Culture Documents
PART 1
Python Database Programming
Interface).
● Let’s see how to connect the MySQL database in Python using the ‘MySQL Connector
Python’ module.
How to Connect to MySQL Database in Python
● Catch exceptions that may occur during this process by importing the Error
class from the MySQL connector module using a from mysql.connector import
Error statement.
● Error class is useful to debug when we failed to connect to MySQL.
● For example, ACCESS DENIED ERROR when the username or password is
wrong.
● The connect() method can throw a Database error exception if one of the required
parameters is wrong. For example, if you provide a database name that is not
present in MySQL.
Create Tables
Python Insert Into MySQL Table
Python Insert Into MySQL Table
Sometimes you need to insert a Python variable value into a table’s column.
For example, in the user signup form user enter his/her details.
We can take those values in Python variables and insert them into a table.
● We can insert Python variables into the table using the prepared statement and
parameterized query.
● Using a parameterized query, we can pass Python variables as a query
parameter in which placeholders (%s) used for parameters.
Insert multiple rows into MySQL table using the cursor’s executemany()
Use the cursor’s executemany() function to insert multiple records into a table.
cursor.executemany(operation, seq_of_params)
This method executes Insert operation against all parameter sequences in the sequence
seq_of_params argument.
Insert multiple rows into MySQL table using the cursor’s executemany()
We need to include lists of tuples in the seq_of_params argument along with the insert
query.
Each tuple inside the list contains a single row that you want to insert.
So we can add as many rows in the list and pass a list to a cursor.executemany()
function along with the insert query.
rows = cursor.fetchmany(size=row_size)
Cursor’s fetchmany() methods return the number of rows specified by size argument, defaults
value of size argument is one.
To select records from my MySQL table using a column name, we only need to change the
cursor creation.
It creates a cursor that returns rows as dictionaries so we can access using column name
(here column name is the key of the dictionary)