import mysql.connector as mysql
db = mysql.connect(
host = "localhost",
user = "root",
passwd = "dbms"
)
print(db)
2.1. Creating Databases
## creating an instance of 'cursor' class which is used to execute the 'SQL' statements in 'Python'
cursor = db.cursor()
## creating a databse called 'datacamp'
## 'execute()' method is used to compile a 'SQL' statement
## below statement is used to create tha 'datacamp' database
cursor.execute("CREATE DATABASE datacamp")
3. Inserting Data
cursor = db.cursor()
## defining the Query
query = "INSERT INTO users (name, user_name) VALUES (%s, %s)"
## storing values in a variable
values = ("Hafeez", "hafeez")
## executing the query with values
cursor.execute(query, values)
## to make final output we have to run the 'commit()' method of the database object
db.commit()
print(cursor.rowcount, "record inserted")
Inserting Multiple Rows
cursor = db.cursor()
## defining the Query
query = "INSERT INTO users (name, user_name) VALUES (%s, %s)"
## storing values in a variable
values = [
("Peter", "peter"),
("Amy", "amy"),
("Michael", "michael"),
("Hennah", "hennah")
]
## executing the query with values
cursor.executemany(query, values)
## to make final output we have to run the 'commit()' method of the database object
db.commit()
print(cursor.rowcount, "records inserted")
4. Select Data
cursor = db.cursor()
## defining the Query
query = "SELECT * FROM users"
## getting records from the table
cursor.execute(query)
## fetching all records from the 'cursor' object
records = cursor.fetchall()
## Showing the data
for record in records:
print(record)
5. Where
cursor = db.cursor()
## defining the Query
query = "SELECT * FROM users WHERE id = 5"
## getting records from the table
cursor.execute(query)
## fetching all records from the 'cursor' object
records = cursor.fetchall()
## Showing the data
for record in records:
print(record)
6. Order By
cursor = db.cursor()
## defining the Query
query = "SELECT * FROM users ORDER BY name"
## getting records from the table
cursor.execute(query)
## fetching all records from the 'cursor' object
records = cursor.fetchall()
## Showing the data
for record in records:
print(record)
7. Delete
cursor = db.cursor()
## defining the Query
query = "DELETE FROM users WHERE id = 5"
## executing the query
cursor.execute(query)
## final step to tell the database that we have changed the table data
db.commit()
8. Update
cursor = db.cursor()
## defining the Query
query = "UPDATE users SET name = 'Kareem' WHERE id = 1"
## executing the query
cursor.execute(query)
## final step to tell the database that we have changed the table data
db.commit()