0% found this document useful (0 votes)
33 views

Python+Mysql 7

This document provides a guide for connecting to a MySQL database from Python by using the mysql-connector library to establish a connection, create a database and tables, perform CRUD operations by executing SQL queries via a cursor, and handle errors from database operations. Code examples are given for installing mysql-connector, connecting to MySQL, defining and creating a database and tables, inserting, selecting, updating, and deleting data from the tables.

Uploaded by

josiasassih4
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Python+Mysql 7

This document provides a guide for connecting to a MySQL database from Python by using the mysql-connector library to establish a connection, create a database and tables, perform CRUD operations by executing SQL queries via a cursor, and handle errors from database operations. Code examples are given for installing mysql-connector, connecting to MySQL, defining and creating a database and tables, inserting, selecting, updating, and deleting data from the tables.

Uploaded by

josiasassih4
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Python + MySQL

a n u l t i m a t e g u i d e

A R U N A R U N I S T O
To use mysql using python you need to
install the library first, use the below code to
install the mysql-connector.

pip install mysql-connector-python

use the below code to access the connector


in your program

import mysql.connector

The below code snippet demonstrates how


to connect to a MySQL database in Python
using the mysql-connector library.

config = {
"user":"root",
'password':'arunisto',
'host':'localhost'
}

db = mysql.connector.connect(**config)
cursor = db.cursor()
config Dictionary:

This dictionary contains the


configuration parameters required to
establish a connection to the MySQL
database.
"user": "root": Specifies the username
for the MySQL server. In this case, it's
"root".
"password": "arunisto": Specifies the
password for the MySQL user specified
(in this case, "root").
"host": "localhost": Specifies the host
where the MySQL server is running.
"localhost" means the MySQL server is
on the same machine as the Python
script.

Database Connection:
db = mysql.connector.connect(**config):
This line establishes a connection to the
MySQL server using the configuration
parameters provided in the config
dictionary.
**config uses dictionary unpacking to
pass the key-value pairs in config as
keyword arguments to the
mysql.connector.connect function.
Creating a Cursor:

cursor = db.cursor(): After establishing


the connection, a cursor object is
created. A cursor allows you to interact
with the database by executing SQL
queries and fetching results.

Creating Database

db_name = 'sample_database'
cursor.execute(
f"CREATE DATABASE IF NOT EXISTS
{db_name} DEFAULT CHARACTER SET 'utf8'"
)
Database Creation Query:

cursor.execute(f"CREATE DATABASE IF
NOT EXISTS {db_name} DEFAULT
CHARACTER SET 'utf8'"): This line
executes an SQL query to create a
database with the name specified in the
db_name variable.
The IF NOT EXISTS clause ensures that
the database is only created if it doesn't
already exist.
DEFAULT CHARACTER SET 'utf8'
specifies the character set for the
database. In this case, it sets the
character set to UTF-8, which supports a
wide range of characters from various
languages.
Creating Tables
tables = {}
tables['logs'] = (
"CREATE TABLE `logs` ("
"`id` int(11) NOT NULL AUTO_INCREMENT,"
"`text` varchar(250) NOT NULL, "
"`user` varchar(250) NOT NULL, "
"`created` datetime NOT NULL DEFAULT
CURRENT_TIMESTAMP, "
"PRIMARY KEY (`id`)"
") ENGINE=InnoDB"
)

cursor.execute("USE {}".format(db_name))
try:
cursor.execute(tables['logs'])
except mysql.connector.Error as err:
if err.errno ==
errorcode.ER_TABLE_EXISTS_ERROR:
print("Table already exists")
else:
print(err.msg)
Defining a Table Schema:

tables['logs']: This line creates a


dictionary entry with the key 'logs'. The
corresponding value is an SQL string
defining the schema for a MySQL table
named 'logs'.
The table has four columns:
id: An auto-incrementing integer field
serving as the primary key.
text: A variable character field with a
maximum length of 250 characters.
user: Another variable character field
with a maximum length of 250
characters.
created: A datetime field that defaults to
the current timestamp.
The table uses the InnoDB storage
engine.
Switching to the Database:

cursor.execute("USE
{}".format(db_name)): This line switches
the MySQL connection to use the
database specified in the db_name
variable. It's important to select the
appropriate database before executing
table creation queries.

Table Creation Attempt:

try:: The code inside this block attempts to


execute the SQL query defined in
tables['logs'].
cursor.execute(tables['logs']): This line
executes the SQL query to create the 'logs'
table in the selected database.

Handling Errors:

except mysql.connector.Error as err:: If there


is a MySQL-related error during the execution
of the cursor.execute(tables['logs']) line, the
code captures the error and assigns it to the
variable err.
errorcode.ER_TABLE_EXISTS_ERROR:: The
code checks if the error number
corresponds to a table already existing in
the database.
If the error indicates that the table
already exists (ER_TABLE_EXISTS_ERROR),
the code prints "Table already exists".
If the error is different from a table
already existing, it prints the error
message.

Adding data into Database:

sql = "INSERT INTO logs(text, user) VALUES


(%s, %s)"
values = ("Added log one", "arun")
cursor.execute(sql, values)
db.commit()
Fetching Data from Database
sql = "SELECT * FROM logs"
cursor.execute(sql)
result = cursor.fetchall()

Fetching single data


sql = "SELECT * FROM logs WHERE id=%s"
id = (1, )
cursor.execute(sql, id)
data = cursor.fetchone()

Updating data
sql = "UPDATE logs SET text = %s WHERE id =
%s"
values = ("text updated", 1)
cursor.execute(sql, values)
db.commit()
Deleting Data

sql = "DELETE FROM logs WHERE id = %s"


id = (1, )
cursor.execute(sql, id)
db.commit()

You might also like