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

Python Mysql

This document provides examples of how to perform common SQL operations using Python and the mysql.connector module, including connecting to a MySQL database, creating and checking for databases, creating and altering tables, inserting, selecting, updating, and deleting data. Code samples are given to demonstrate each operation.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
96 views

Python Mysql

This document provides examples of how to perform common SQL operations using Python and the mysql.connector module, including connecting to a MySQL database, creating and checking for databases, creating and altering tables, inserting, selecting, updating, and deleting data. Code samples are given to demonstrate each operation.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

sudo apt-get install python3-mysql.

connector

1)Create Connection
Start by creating a connection to the database.
Use the username and password from your MySQL database:

demo_mysql_connection.py:

import mysql.connector

mydb = mysql.connector.connect(

host="localhost",

user="yourusername",

passwd="yourpassword"

print(mydb)
2)Creating a Database
To create a database in MySQL, use the "CREATE DATABASE" statement:

Example
create a database named "mydatabase":

import mysql.connector

mydb = mysql.connector.connect(

host="localhost",

user="yourusername",

passwd="yourpassword"

mycursor = mydb.cursor()

mycursor.execute("CREATE DATABASE mydatabase")

If the above code was executed with no errors, you have successfully created a database.
3)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",

passwd="yourpassword"

mycursor = mydb.cursor()

mycursor.execute("SHOW DATABASES")
for x in mycursor:

print(x)
4)Try connecting to the database "mydatabase":

import mysql.connector

mydb = mysql.connector.connect(

host="localhost",

user="yourusername",

passwd="yourpassword",

database="mydatabase"

5)Primary Key
When creating a table, you should also create a column with a unique key for each record.
This can be done by defining a PRIMARY KEY.
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.

Example
Create primary key when creating the table:
import mysql.connector

mydb = mysql.connector.connect(

host="localhost",

user="yourusername",

passwd="yourpassword",

database="mydatabase"

mycursor = mydb.cursor()

mycursor.execute("CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(255), address VARCHAR(255))")

If the table already exists, use the ALTER TABLE keyword:


6) ALTER TABLE

Example
Create primary key on an existing table:

import mysql.connector

mydb = mysql.connector.connect(

host="localhost",

user="yourusername",

passwd="yourpassword",

database="mydatabase"

mycursor = mydb.cursor()

mycursor.execute("ALTER TABLE customers ADD COLUMN id INT AUTO_INCREMENT

PRIMARY KEY")
Insert a single row

import mysql.connector

mydb = mysql.connector.connect(

host="localhost",

user="yourusername",

passwd="yourpassword",

database="mydatabase"

mycursor = mydb.cursor()

sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"

val = ("John", "Highway 21")

mycursor.execute(sql, val)

mydb.commit()

print(mycursor.rowcount, "record inserted.")

Run example »
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:

Example
Fill the "customers" table with data:

import mysql.connector

mydb = mysql.connector.connect(

host="localhost",

user="yourusername",

passwd="yourpassword",

database="mydatabase"

mycursor = mydb.cursor()

sql = "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')

]
mycursor.executemany(sql, val)

mydb.commit()

print(mycursor.rowcount, "was inserted.")


Select From a Table
To select from a table in MySQL, use the "SELECT" statement:

Example
Select all records from the "customers" table, and display the result:

import mysql.connector

mydb = mysql.connector.connect(

host="localhost",

user="yourusername",

passwd="yourpassword",

database="mydatabase"

mycursor = mydb.cursor()

mycursor.execute("SELECT * FROM customers")


myresult = mycursor.fetchall()

for x in myresult:

print(x)
Delete Record
You can delete records from an existing table by using the "DELETE FROM" statement:

Example
Delete any record where the address is "Mountain 21":

import mysql.connector

mydb = mysql.connector.connect(

host="localhost",

user="yourusername",

passwd="yourpassword",

database="mydatabase"

mycursor = mydb.cursor()

sql = "DELETE FROM customers WHERE address = 'Mountain 21'"


mycursor.execute(sql)

mydb.commit()

print(mycursor.rowcount, "record(s) deleted")


Update Table
You can update existing records in a table by using the "UPDATE" statement:

Example
Overwrite the address column from "Valley 345" to "Canyoun 123":

import mysql.connector

mydb = mysql.connector.connect(

host="localhost",

user="yourusername",

passwd="yourpassword",

database="mydatabase"

mycursor = mydb.cursor()

sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 345'"
mycursor.execute(sql)

mydb.commit()

print(mycursor.rowcount, "record(s) affected")

You might also like