Key Points
Learn how to use the PyMySQL library
Development Mindset
Pre-Class Preparation
Required Libraries
Server input
sudo pip3 install pymysql
Local host input
pip install pymysql
Course Content
Pymysql
1. Data query
After using Navicat to create a form in the database and add some data, we try to query all the data of the form in the database:
import pymysql # Connect to a database conn = pymysql.connect(host='116.62.221.174',user="user1",password="123456",database="jdy_api",charset="utf8") # Get a cursor object that can execute SQL statements cursor = conn.cursor() sql = "SELECT * FROM personinformation" try: # Execute SQL statements cursor.execute(sql) conn.commit() except Exception as e: print(e) conn.rollback() # Get the returned data data = cursor.fetchall() # Close the cursor object cursor.close() # Close the database connection conn.close() print(data)
2. Define a function to insert data
import pymysql def insert_into_mysql(a,c,b): # Connect to a database conn = pymysql.connect(host='116.62.221.174',user="user1",password="123456",database="jdy_api",charset="utf8") # Get a cursor object that can execute SQL statements cursor = conn.cursor() sql = "insert into personinformation values ('%s','%s','%s')" % (a,b,c) print(sql) try: # Execute SQL statements cursor.execute(sql) conn.commit() except Exception as e: print(e) conn.rollback() # Get the returned data result = cursor.fetchone() # Close the cursor object cursor.close() # Close the database connection conn.close() print(result)
Development Mindset
Modular thinking (import)
Exception handling mindset
o Exception handling
o Breakpoint debugging (step)
import json request_data = {"data": [{"aaa": 123, "bbb":234}]} data_ = request_data['data'] data_0 = data_[0] _id= data_0["_id"]