Devdit
 

Python เพิ่ม ลบ แก้ไข แสดงข้อมูล MySQL (Python CRUD)

3.1K

บทความนี้สอนเขียน Python เพิ่ม ลบ แก้ไข และแสดงข้อมูล จาก MySQL (Python CRUD) โดยโปรแกรมตัวนี้มีความสามารถดังนี้

 

ความสามารถโปรแกรม

1. แสดงข้อมูล (SELECT) ทำหน้าที่แสดงข้อมูลในตาราง product

2. เพิ่มข้อมูล (INSERT) ทำหน้าที่เพิ่มข้อมูลลงในตาราง product

3. แก้ไขข้อมูล (UPDATE) ทำหน้าที่แก้ไขข้อมูลในตาราง product

4. ลบข้อมูล (DELETE) ทำหน้าที่ลบข้อมูลในตาราง product

5. ค้นหาข้อมูล (SEARCH) ทำหน้าที่ค้นหา และแสดงข้อมูลในตาราง product

6. ออกจากโปรแกรม (EXIT) ทำหน้าที่ออกจากโปรแกรม เมื่อจบการทำงาน

 

เริ่มต้นเขียนโปรแกรม Python CRUD

1. สร้างฐานข้อมูล ชื่อ db_example และรัน SQL ด้านล่างเพื่อสร้างตารางชื่อ product และเพิ่มข้อมูลลงในตารางดังกล่าวทั้งหมด 3 ข้อมูล

CREATE TABLE product (
id int(11) NOT NULL AUTO_INCREMENT,
title char(255) NOT NULL,
price int(11) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT INTO product (id, title, price) VALUES
(NULL, 'Pencil', 10),
(NULL, 'Pen', 15),
(NULL, 'Ruler', 15)

 

2. สร้างไฟล์ crud.py และเขียนโค้ดทั้งหมดไว้ในไฟล์ดังกล่าว

 

3. สร้าง function สำหรับหน้าจอแรกของโปรแกรม สหรับ แสดงข้อมูล เพิ่มข้อมูล แก้ไขข้อมูล ลบข้อมูล ค้นหาข้อมูล และออกจากโปรแกรม

def screen():
    action = 0
    while action != 6:
        print("\n======= Python CRUD =======")
        print("1. SELECT")
        print("2. INSERT")
        print("3. UPDATE")
        print("4. DELETE")
        print("5. SEARCH")
        print("6. EXIT")
        print("===========================")
        try:
            action = int(input("Please input number: "))
        except:
            action = 0
        
        if( action == 1 ):
            select()
        elif( action == 2 ):
            insert()
        elif( action == 3 ):
            update()        
        elif( action == 4 ):
            delete()
        elif( action == 5 ):
            search()        
        elif( action == 6 ):
            exit_()        
        else:
            print("Error, Please input number 1-5")

หน้าจอโปรแกรมจะมีเมนูทั้งหมด 6 เมนู คือ SELECT, INSERT, UPDATE, DELETE, SEARCH และ EXIT ซึ่งผู้ใช้งานต้องใส่ตัวเลข 1 - 6 ที่ต้องการทำงาน โดยหลักการเขียนโปรแกรมมีการใช้ลูป while เช็คเงื่อนไขหากมีการใส่เลข 6 โปรแกรมจะจบการทำงาน

 

4. สร้าง function สำหรับเชื่อมต่อฐานข้อมูล

import mysql.connector

def connect():
    return mysql.connector.connect(user='root', password='', host='localhost', database='db_example', port=3306)

function connect ทำหน้าที่เชื่อมต่อฐานข้อมูล MySQL โดยกำหนดให้ user คือ root, password ไม่ได้กำหนด, host คือ localhost (Python และ MySQL อยู่ในเครื่องเดียวกัน), database คือ db_example และ port เท่ากับ 3306 (Default Port)

 

5. สร้าง function สำหรับแสดงข้อมูล (SELECT)

def select():
    conn = connect()
    sql = " SELECT * FROM product "
    cur = conn.cursor()
    cur.execute( sql )
    records = cur.fetchall()
    for row in records:
        print(str(row[0])+"\t"+str(row[1])+"\t\t"+str('{:.2f}'.format(row[2])))

    conn.close()

function select ทำหน้าที่แสดงข้อมูล (SELECT) ใช้คำสั่ง SELECT * FROM product เพื่อดึงข้อมูลทั้งหมด และสร้างตัวแปร records เพื่อรับข้อมูลทั้งหมดผ่านคำสั่ง fetchall จากนั้น นำตัวแปร records ไปวนลูปเพื่อแสดงข้อมูลแต่ละแถวออกมาด้วย for loop

 

6. สร้าง function สำหรับเพิ่มข้อมูล (INSERT)

def insert():
    try:
        title = input("\nPlease input title: ")
        price = int(input("Please input price: "))
    except:
        title = ''
        price = 0
    
    if( title != '' and price > 0 ):
        conn = connect()
        cur = conn.cursor()
        cur.execute( " INSERT INTO product ( id, title, price ) VALUES ( NULL, %s, %s ) ", ( title, price, ) )
        conn.commit()
        conn.close()
        print(cur.rowcount, "record(s) insert\n") 

function insert ทำหน้าที่เพิ่มข้อมูล (INSERT) มีการรับค่าจากผู้ใช้งาน 2 ค่า คือ ชื่อ (title) และ ราคา (price) จากนั้นนำตัวแปรทั้ง 2 ไปใส่ในชุดคำสั่ง SQL INSERT INTO เพื่อเพิ่มข้อมูลลงในตาราง product

 

7. สร้าง function สำหรับแก้ไขข้อมูล (UPDATE)

def update():
    try:
        id = int(input("\nPlease input id to update: "))
    except:
        id = 0
    
    if( id > 0 ):
        conn = connect()
        cur = conn.cursor()
        cur.execute( " SELECT * FROM product WHERE ( id = %s ) ", ( id, ) )
        record = cur.fetchone()
        print( record )    

        if( record != None ):
            try:
                title = input("\nPlease input title: ")
                price = int(input("Please input price: "))
            except:
                title = ''
                price = 0 

            if( title != '' and price > 0 and id > 0 ):
                cur.execute( " UPDATE product SET title = %s, price = %s WHERE ( id = %s ) ", ( title, price, id ) )
                conn.commit()
                print(cur.rowcount, "record(s) updated\n") 

        conn.close()

function update ทำหน้าที่แก้ไขข้อมูล (UPDATE) เริ่มต้นจากการรับค่าหมายเลขสินค้า (id) เพื่อมาค้นหาข้อมูล กรณีถ้ามีข้อมูลจะรับข้อมูลชื่อ (title) และราคา (price) และนำไปใส่ในคำสั่ง SQL UPDATE เพื่อแก้ไขข้อมูลในตาราง product

 

8. สร้าง function สำหรับลบข้อมูล (DELETE)

def delete():
    try:
        id = int(input("\nPlease input id to delete: "))
    except:
        id = 0

    if( id > 0 ):
        conn = connect()
        cur = conn.cursor()
        cur.execute( "DELETE FROM product WHERE ( id=%s )", (id,) )
        conn.commit()
        conn.close()
        print(cur.rowcount, "record(s) deleted\n")

function delete ทำหน้าที่ลบข้อมูล (DELETE) โดยรับค่าหมายเลขสินค้า (id) ที่ต้องการลบ จากผู้ใช้งาน และนำไปใส่ในเงื่อนไข WHERE ของคำสั่ง SQL DELETE FROM เพื่อลบข้อมูล 

 

9. สร้าง function สำหรับค้นหาข้อมูล

def search():
    try:
        search = input("\nPlease input search: ")
    except:
        search = ''

    if( len(search) != 0 ):
        conn = connect()
        cur = conn.cursor()
        cur.execute( "SELECT * FROM product WHERE ( title LIKE %s )", ("%"+search+"%",) )
        records = cur.fetchall()
        for row in records:
            print(str(row[0])+"\t"+str(row[1])+"\t\t"+str('{:.2f}'.format(row[2]))) 

function search ทำหน้าที่ค้นหาข้อมูล (SEARCH) โดยรับข้อความที่ต้องการค้นหาจากผู้ใช้งาน และเก็บไว้ในตัวแปร search จากนั้นนำตัวแปร search ไปใช้งานร่วมกับคำสั่ง SQL ในส่วนของ SELECT เงื่อนไข WHERE LIKE โดยข้อมูลที่ค้นหาเจอจะถูกเก็บไว้ในตัวแปร records และถูกวนลูปออกมาผ่าน for loop

 

10. สร้าง function สำหรับออกจากโปรแกรม

def exit_():
    print("Bye..")
    exit()

function exit_ จะพิมพ์ข้อความ Bye.. และใช้คำสั่ง exit เพื่อออกจากโปรแกรม

 

11. เรียกใช้งานโปรแกรมผ่าน function screen

screen()

ส่วนนี้ คือ การเรียก function screen ขึ้นมาเพื่อเริ่มต้นการทำงานของโปรแกรม Python CRUD

 

ตัวอย่าง สำหรับแปลง Python เป็น .exe

 

ตัวอย่าง โปรแกรมแบบเต็ม

import mysql.connector

def connect():
    return mysql.connector.connect(user='root', password='', host='localhost', database='db_example', port=3306)

def select():
    conn = connect()
    sql = " SELECT * FROM product "
    cur = conn.cursor()
    cur.execute( sql )
    records = cur.fetchall()
    for row in records:
        print(str(row[0])+"\t"+str(row[1])+"\t\t"+str('{:.2f}'.format(row[2])))

    conn.close()

def insert():
    try:
        title = input("\nPlease input title: ")
        price = int(input("Please input price: "))
    except:
        title = ''
        price = 0
    
    if( title != '' and price > 0 ):
        conn = connect()
        cur = conn.cursor()
        cur.execute( " INSERT INTO product ( id, title, price ) VALUES ( NULL, %s, %s ) ", ( title, price, ) )
        conn.commit()
        conn.close()
        print(cur.rowcount, "record(s) insert\n") 

def update():
    try:
        id = int(input("\nPlease input id to update: "))
    except:
        id = 0
    
    if( id > 0 ):
        conn = connect()
        cur = conn.cursor()
        cur.execute( " SELECT * FROM product WHERE ( id = %s ) ", ( id, ) )
        record = cur.fetchone()
        print( record )    

        if( record != None ):
            try:
                title = input("\nPlease input title: ")
                price = int(input("Please input price: "))
            except:
                title = ''
                price = 0 

            if( title != '' and price > 0 and id > 0 ):
                cur.execute( " UPDATE product SET title = %s, price = %s WHERE ( id = %s ) ", ( title, price, id ) )
                conn.commit()
                print(cur.rowcount, "record(s) updated\n") 

        conn.close()

def delete():
    try:
        id = int(input("\nPlease input id to delete: "))
    except:
        id = 0

    if( id > 0 ):
        conn = connect()
        cur = conn.cursor()
        cur.execute( "DELETE FROM product WHERE ( id=%s )", (id,) )
        conn.commit()
        conn.close()
        print(cur.rowcount, "record(s) deleted\n")

def search():
    try:
        search = input("\nPlease input search: ")
    except:
        search = ''

    if( len(search) != 0 ):
        conn = connect()
        cur = conn.cursor()
        cur.execute( "SELECT * FROM product WHERE ( title LIKE %s )", ("%"+search+"%",) )
        records = cur.fetchall()
        for row in records:
            print(str(row[0])+"\t"+str(row[1])+"\t\t"+str('{:.2f}'.format(row[2])))        

def exit_():
    print("Bye..")
    exit()

def screen():
    action = 0
    while action != 6:
        print("\n======= Python CRUD =======")
        print("1. SELECT")
        print("2. INSERT")
        print("3. UPDATE")
        print("4. DELETE")
        print("5. SEARCH")
        print("6. EXIT")
        print("===========================")
        try:
            action = int(input("Please input number: "))
        except:
            action = 0
        
        if( action == 1 ):
            select()
        elif( action == 2 ):
            insert()
        elif( action == 3 ):
            update()        
        elif( action == 4 ):
            delete()
        elif( action == 5 ):
            search()        
        elif( action == 6 ):
            exit_()        
        else:
            print("Error, Please input number 1-5")

screen()
แก้ไข 2 ปีที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ