Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

Bài 8 Truy xuất dữ liệu MySQL trong Python

Bài 8 - Truy xuất dữ liệu MySQL trong Python 1


MỤC TIÊU
• Giới thiệu

• Kết nối tới MySQL

• Truy vấn dữ liệu

• Các thao tác khác

Bài 8 - Truy xuất dữ liệu MySQL trong Python 2


Giớ thiệu
• Python có thể làm việc với nhiều loại database khác nhau, một trong những database
phổ biến nhất là MySQL.

• Để làm việc với MySQL chúng ta phải cài Driver “MySQL Connector” theo lệnh sau

C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>python -m pip


install mysql-connector-python

Bài 8 - Truy xuất dữ liệu MySQL trong Python 3


Kết nối với MySQL trong Python

# import thư viện # import thư viện


import mysql.connector import mysql.connector
# kết nối tới mysql # kết nối tới mysql và làm việc với
connection=mysql.connector.connect( database ‘bookstore’
host="localhost", connection=mysql.connector.connect(
user="root", host="localhost",
password="" database="bookstore",
) user="root",
password=""
)

Bài 8 - Truy xuất dữ liệu MySQL trong Python 4


Truy vấn dữ liệu
# import thư viện # nhận kết quả dòng đầu tiên
import mysql.connector # record=cursor.fetchone()
# kết nối tới mysql # nhận tất cả các dòng
connection=mysql.connector.connect( records=cursor.fetchall()
host="localhost", print(" Danh mục sách ")
database="bookstore", print("--------------------------------------------")
user="root", print("\tMã\t\tTên")
password="" print("--------------------------------------------")
) # đọc dữ liệu
# tạo và lấy con trỏ của mysql for row in records:
cursor=connection.cursor() print("|",row[0],"\t\t|", row[1])
# tạo câu truy vấn # đóng kết nối
sql="select * from products“ connection.close()
# thực thi câu truy vấn # đóng con trỏ
cursor.execute(sql) cursor.close()

Bài 8 - Truy xuất dữ liệu MySQL trong Python 5


Các thao tác dữ liệu

# import thư viện # đinh nghĩa hàm thêm dữ liệu


def insert_category():
import mysql.connector con=connectdatabase()
# định nghĩa hàm kết nối cursor=con.cursor()
insert_category="insert into categories(categ
def connectdatabase(): oryname,allowed) values(%s,%s)"
# kết nối tới database bookstore trong mysql # nhập dữ liệu từ bàn phím
name=input("Tên chủ đề:")
connection=mysql.connector.connect( allow=input("Hiển thị:")
host="localhost", # thực thi
cursor.execute(insert_category,(name, allow))
database="bookstore", # lấy mã số vừa thêm
user="root", lastrow=cursor.lastrowid
print(lastrow)
password="" # ghi dữ liệu vào database
) con.commit()
# đóng kết nối
return connection con.close()
cursor.close()

Bài 8 - Truy xuất dữ liệu MySQL trong Python 6


Các thao tác dữ liệu
def delete_category(): def update_category():
con=connectdatabase() con=connectdatabase()
cursor=con.cursor()
cursor=con.cursor()
update_category="update categories set categoryname=%s
del_category="delete from categories
, allowed=%s where categoryid=%s"
where categoryid=%s" # nhập dữ liệu từ bàn phím
# nhập dữ liệu từ bàn phím id=input("Mã chủ đề:")
id=input("Mã cần xóa:") name=input("Tên chủ đề:")
# thực thi allow=input("Hiển thị:")
# thực thi
cursor.execute(del_category,(id,))
cursor.execute(update_category,(name, allow,id))
# ghi dữ liệu vào database
# ghi dữ liệu vào database
con.commit()
con.commit()
# đóng kết nối # đóng kết nối
con.close() con.close()
cursor.close() cursor.close()

Bài 8 - Truy xuất dữ liệu MySQL trong Python 7


Các thao tác với database

import mysql.connector # định nghĩa hàm tạo database


# định nghĩa hàm kết nối def create_database(db):
def connectdatabase(db=''): con=connectdatabase()
if(db==''): cursor=con.cursor()
connection=mysql.connector.connect( cursor.execute('create database if not exists '+d
host='localhost', b)
user='root', print('Tạo thành công')
password='' # định nghĩa hàm tạo bảng
) def create_table():
print('database not exists') con=connectdatabase('demo111')
else: cursor=con.cursor()
connection=mysql.connector.connect( cursor.execute('create table if not exists produc
host='localhost', t(productid varchar(10) primary key,productname varch
user='root', ar(100),price int)')
password='', print('Tạo thành công')
database=db # test
) create_database('demo111')
print('database is ',db) create_table()
return connection

Bài 8 - Truy xuất dữ liệu MySQL trong Python 8


HỎI ĐÁP

Bài 8 - Truy xuất dữ liệu MySQL trong Python 9


Bài 8 - Truy xuất dữ liệu MySQL trong Python 10
238 Hoàng Quốc Việt, Bắc Từ Liêm, Hà Nội

0968.27.6996

tuyensinh@bachkhoa-aptech.edu.vn

www.bachkhoa-aptech.edu.vn

Bài 8 - Truy xuất dữ liệu MySQL trong Python 11

You might also like