Python CRUD demo

Before you start

Setup your environment

Before you start, make sure you have downloaded and installed the following software.

  1. Make sure you have already installed and launched MatrixOne.
  2. Make sure you have already installed Python 3.8(or plus) version.

    1. #To check with Python installation and its version
    2. python3 -V
  3. Make sure you have already installed MySQL.

  4. Download and install pymysql and cryptography tool.

    1. pip3 install pymysql
    2. pip3 install cryptography
    3. #If you are in China mainland and have a low downloading speed, you can speed up the download by following commands.
    4. pip3 install pymysql -i https://pypi.tuna.tsinghua.edu.cn/simple
    5. pip3 install cryptography -i https://pypi.tuna.tsinghua.edu.cn/simple

As we have explained how to connect to MatrixOne by pymysql in the other tutorial, we will focus on the CRUD(Create, Read, Update, Delete) implementations in this tutorial.

Create Table

Firstly we create a text file named create.py, and put the following code:

  1. #!/usr/bin/python3
  2. import pymysql.cursors
  3. SQL_CONNECTION = pymysql.connect(
  4. host='127.0.0.1',
  5. port=6001,
  6. user='root',
  7. password = "111",
  8. db='test',
  9. cursorclass=pymysql.cursors.DictCursor,
  10. autocommit=True
  11. )
  12. SQL = "CREATE TABLE cars (id INT NOT NULL AUTO_INCREMENT, car_model VARCHAR(45) NULL,car_brand VARCHAR(45) NULL,PRIMARY KEY (`id`))"
  13. with SQL_CONNECTION.cursor() as cursor:
  14. try:
  15. sql_exec = cursor.execute(SQL)
  16. print("Table created")
  17. except (pymysql.Error, pymysql.Warning) as e:
  18. print(f'error! {e}')
  19. finally:
  20. SQL_CONNECTION.close()

Execute this python file by a terminal with the command line below. This will create a table cars in MatrixOne inside database test.

  1. > python3 create.py
  2. Table created

We can verify the table creation with MySQL client.

  1. mysql> show tables;
  2. +----------------+
  3. | tables_in_test |
  4. +----------------+
  5. | cars |
  6. +----------------+
  7. 1 row in set (0.03 sec)
  8. mysql> show create table cars;
  9. +-------+----------------------------------------------------------------------------------------------------------------------------------------------------------+
  10. | Table | Create Table |
  11. +-------+----------------------------------------------------------------------------------------------------------------------------------------------------------+
  12. | cars | CREATE TABLE `cars` (
  13. `id` INT NOT NULL AUTO_INCREMENT,
  14. `car_model` VARCHAR(45) DEFAULT NULL,
  15. `car_brand` VARCHAR(45) DEFAULT NULL,
  16. PRIMARY KEY (`id`)
  17. ) |
  18. +-------+----------------------------------------------------------------------------------------------------------------------------------------------------------+
  19. 1 row in set (0.03 sec)

Insert

Secondly we create a text file named insert.py, and put the following code:

  1. #!/usr/bin/python3
  2. import pymysql.cursors
  3. SQL_CONNECTION = pymysql.connect(
  4. host='127.0.0.1',
  5. port=6001,
  6. user='root',
  7. password = "111",
  8. db='test',
  9. cursorclass=pymysql.cursors.DictCursor,
  10. autocommit=True
  11. )
  12. SQL = "INSERT INTO cars(car_model, car_brand) VALUES ('accord', 'honda')"
  13. with SQL_CONNECTION.cursor() as cursor:
  14. try:
  15. sql_exec = cursor.execute(SQL)
  16. if sql_exec:
  17. print(sql_exec)
  18. print("Record Added")
  19. else:
  20. print(sql_exec)
  21. print("Not Added")
  22. except (pymysql.Error, pymysql.Warning) as e:
  23. print(f'error! {e}')
  24. finally:
  25. SQL_CONNECTION.close()

Executing the following code will insert a record in the cars table, then we verify in mysql client to check if the record is inserted.

  1. > python3 insert.py
  2. 1
  3. Record Added
  1. mysql> select * from cars;
  2. +------+-----------+-----------+
  3. | id | car_model | car_brand |
  4. +------+-----------+-----------+
  5. | 1 | accord | honda |
  6. +------+-----------+-----------+
  7. 1 row in set (0.03 sec)

Select

Thirdly we create a text file named read.py, and put the following code:

  1. #!/usr/bin/python3
  2. import pymysql.cursors
  3. SQL_CONNECTION = pymysql.connect(
  4. host='127.0.0.1',
  5. port=6001,
  6. user='root',
  7. password = "111",
  8. db='test',
  9. cursorclass=pymysql.cursors.DictCursor,
  10. autocommit=True
  11. )
  12. SQL = "SELECT * FROM cars"
  13. with SQL_CONNECTION.cursor() as cursor:
  14. try:
  15. sql_exec = cursor.execute(SQL)
  16. if sql_exec:
  17. print(sql_exec)
  18. print(cursor.fetchall())
  19. else:
  20. print(sql_exec)
  21. print("No Record")
  22. except (pymysql.Error, pymysql.Warning) as e:
  23. print(f'error! {e}')
  24. finally:
  25. SQL_CONNECTION.close()

Executing this code will select and return all records in the cars table.

  1. > python3 read.py
  2. 1
  3. [{'id': 1, 'car_model': 'accord', 'car_brand': 'honda'}]

Update

Fourthly we create a text file named update.py, and put the following code:

  1. #!/usr/bin/python3
  2. import pymysql.cursors
  3. SQL_CONNECTION = pymysql.connect(
  4. host='127.0.0.1',
  5. port=6001,
  6. user='root',
  7. password = "111",
  8. db='test',
  9. cursorclass=pymysql.cursors.DictCursor,
  10. autocommit=True
  11. )
  12. SQL = "UPDATE cars SET car_model = 'explorer', car_brand = 'ford' WHERE id = '1'"
  13. with SQL_CONNECTION.cursor() as cursor:
  14. try:
  15. sql_exec = cursor.execute(SQL)
  16. if sql_exec:
  17. print(sql_exec)
  18. print("Record Updated")
  19. else:
  20. print(sql_exec)
  21. print("Not Updated")
  22. except (pymysql.Error, pymysql.Warning) as e:
  23. print(f'error! {e}')
  24. finally:
  25. SQL_CONNECTION.close()

Executing this code will update the record with id 1, then we verify in mysql client to check if the record is updated.

  1. > python3 update.py
  2. 1
  3. Record Updated
  1. mysql> select * from cars;
  2. +------+-----------+-----------+
  3. | id | car_model | car_brand |
  4. +------+-----------+-----------+
  5. | 1 | explorer | ford |
  6. +------+-----------+-----------+
  7. 1 row in set (0.02 sec)

Delete

Finally we create a text file named delete.py, and put the following code:

  1. #!/usr/bin/python3
  2. import pymysql.cursors
  3. SQL_CONNECTION = pymysql.connect(
  4. host='127.0.0.1',
  5. port=6001,
  6. user='root',
  7. password = "111",
  8. db='test',
  9. cursorclass=pymysql.cursors.DictCursor,
  10. autocommit=True
  11. )
  12. SQL = "DELETE FROM cars WHERE id = '1'"
  13. with SQL_CONNECTION.cursor() as cursor:
  14. try:
  15. sql_exec = cursor.execute(SQL)
  16. if sql_exec:
  17. print(sql_exec)
  18. print("Record Deleted")
  19. else:
  20. print(sql_exec)
  21. print("Not Deleted")
  22. except (pymysql.Error, pymysql.Warning) as e:
  23. print(f'error! {e}')
  24. finally:
  25. SQL_CONNECTION.close()

Executing this code will delete the record with id 1, then we verify in mysql client to check if the record is updated.

  1. > python3 delete.py
  2. 1
  3. Record Deleted
  1. mysql> select * from cars;
  2. Empty set (0.03 sec)