Python Self study planning , How to learn programming step by step [ chart ]
I believe there are many people learning python When , Always holding a cavity of hot blood , And then in b Watch the teaching video of several station owners , Or collected some materials and books . After a while , You lose the motivation to continue learning .
Through my usual observation , Find out you want to learn python Many of the . But a lot of people just stay on the surface , It's always three days fishing , Two days drying net . Most people just stay on their lips when they study , even Python None of the running environments of . If Python The running environment is not installed , Do you have to rely on your brain to make up the code ? If you really want to learn by yourself Python, The installation environment should be good , Type out the code line by line in the book , This is how programmers should learn .
You don't have to collect too much information when you study , Every book has its own knowledge system . Choose a good book and eat it slowly , Type all the code above , It's definitely better than just staring at the video learning effect of doing nothing .
Python Self study planning , How to learn programming step by step [ chart ]
I have some. Python Learning materials , There are friends who want to learn , You can talk to me .
Python Database programming
DB-API
Python Provides a unified DB-API Interface to access the database ,DB-API The interface blocks all the underlying details of accessing different databases ,Python Application calls DB-API Interface can realize the access to different databases .
DB-API The interface mainly contains three class modules , Namely Connection、Cursor、Exception.Connection Class module mainly realizes the connection of database 、 Commit and roll back of database operation transaction , meanwhile Connection Will create a Cursor object ;Cursor Class modules can execute SQL command , Yes SQL The result set of the query is processed ;Exception Class module provides information for exceptions and errors during database operations .
Connection Class module
Connect to database
Connection Class modules provide connect Constructors , Used to create a Connection object , This object will connect to the running database . The following table calls connect When the method is used , Need the parameter passed in .
The sample code for connecting to the database is as follows :import pymysql as mysqlconn = mysql .connect(dsn='myhost:MYDB', user='guido', password='234$')
among ,conn Used to receive connect Method Connection object ,“myhost:MYDB” Is the access address of the database server ,“guido” Is the user name to log in to the database server ,“234$” Is the user password to log in to the database server .
Close the database
When you need to close a database connection , You can call Connection Object's close Method to close the database connection , Release database connection resources .
The sample code of closing database connection is as follows :conn.close()
Commit database transaction
If you need to commit a pending database transaction to the database , You can call Connection Object's commit Method to commit a pending transaction .
The sample code of commit transaction is as follows :conn. commit()
Roll back the current transaction
If an exception or error occurs during the processing of a transaction committed to the database , It is necessary to roll back the database operation that has been carried out , You can call Connection Object's rollback Method to roll back the currently committed transaction .
The sample code for rolling back a transaction is as follows :conn. rollback ()
establish Cursor object
After a successful database connection , Need to get Cursor object , adopt Cursor Object to execute SQL command . call Connection Object's cursor Method to create a Cursor object .
establish Cursor The object sample code is as follows :cursor = conn.cursor()
Cursor Class module
perform SQL command
Access to the database is mainly to add, delete, modify and query the database table records , Add, delete, modify and query all need to be carried out SQL command . call Cursor Object's execute Method can execute SQL command . The following table calls execute When the method is used , Need the parameter passed in .
perform SQL The command sample code is as follows :# obtain Cursor object cursor = conn..cursor()# SQL Inquire about sql = "select * from table_name where 1=1"try:# perform SQL sentence cursor.execute(sql)# Commit to database execution except:# Rollback on error

 brief introduction :Python Is a cross platform computer programming language . It's a high-level combination of explanatory 、 Compilability 、 Interactive and object-oriented scripting language . After winning the championship 600 word https://www.yuananren.com/guanhougan/11279.html Originally designed to write automated scripts (shell), With the continuous update of the version and the addition of new language features , The more it's used for independent 、 Development of large projects .

Cursor Other main methods of objects
The following table lists them Cursor Other main methods of objects .
Cursor Object properties
The following table lists them Cursor The main properties of the object .
Exception Class module
Exception Class module includes exception and error information that may occur during database access , See the following table for exception and error information .
How to use DB-API Interface ?
Python For different database management systems to provide the corresponding DB-API Interface , This course is based on MySQL Database, for example , Other database systems can use the corresponding DB-API Interface .
install MySQL Database interface pymysql
pymysql yes Python Provided , Used to connect to MySQL Database DB-API Interface . Use... In the program pymysql Before , You need to install pymysql.
Windows 10 Operating system installation pymysql, start-up Windows Command line window , Enter the following command in the window :
pip install pymysql
ubuntu Operating system installation pymysql, Start the command line terminal , Enter the following command in the terminal window :
Use... In the program pymysql
Import pymysql# Use try Statement to catch database errors # Connect to database conn = mysql.connect(host='localhost',user='root',password='123456',database='shop')print(conn)except Exception as e:# The connection fails , Output error message print(e)
Add, delete, modify and query database tables
Query database table records
Cursor Object to perform SQL After query statement , Will be returned as a result set , All the records of the query database will be stored in the result set .
Case study 1: Query all records in the database table
Inquire about shop database shoper All the records of the table .# Define database connection functions def connect_database():password='~123456q',return connreturn "error"# Program entrance if name == 'main':conn = connect_database()if conn == "error":print(" Database connection error ")else:# obtain Curso object # Use execute Method execution SQL Query statement cursor.execute("SELECT * FROM shoper")# Get all result sets result = cursor.fetchall()# Traverse each row of the result set for row in result:print(row)# Close database connection finally:cursor.close()
Code reading
Code using import Statement import pymysql library .
The code defines the function connect_database(), This function call pymysql Library connect Functions connect to local MySQL database , And return to the created Connection object . The function uses try Statement to catch exceptions that may occur when connecting to a database , If the exception is caught , Function output exception information , And back to error.
Body code calls connect_database() Function to connect to the database and create Connection object , call Connection Object's cursor Method to get Cursor object , call Cursor object execute Method execution SQL Query statement ,execute Method will return SQL The result set after the query statement is executed , The data type returned is tuple , Traversing tuples can output every record in the result set .
Add database table record
Adding a database table record is to add a new record to the database table , Adding records is done by SQL Of INSERT Statement complete ,Cursor Object's execute Method execution SQL Of INSERT sentence . all SQL After statement execution , call Cursor Object's commit Method to commit a transaction to the database , If an exception occurs in the transaction , Need to be in except In the block , call Cursor Object's rollback Method to roll back the transaction .
Case study 1: Add record to database table
import traceback# Define the added record shopers = ({"id": "0010","userId": "001","name": " East China flagship store ","brief": " Digital products ","log": "","shopMoney":0,"createDate":"2020-05-12"},{"id": "0011","name": " South China flagship store ","brief": " Home appliances ","createDate":"2020-05-12"} # Define record adding function def add(conn,cursor):# Add records SQL sentence sql = "INSERT INTO shoper(id,userId,name,brief,log,shopMoney,createDate)\VALUES ('%s','%s','%s','%s','%s',%d,'%s')"# perform sql Insert statement for shop in shopers:cursor.execute(sql % (shop["id"],shop["userId"],shop["name"],shop["brief"],shop["log"],shop["shopMoney"],shop["createDate"]))# Roll back transactions committed to the database traceback.print_exc()add(conn,cursor)# rowcount yes Cursor Object properties # rowcount Records the number of record lines that were most recently operated or affected print("%d Record added successfully " % (cursor.rowcount))
Code imported traceback modular , When an exception occurs in the output database , Error message for output details .
Before adding database table records , Use tuples to store the record data that needs to be added , Each element of the tuple is a record , Each record is stored in a dictionary , Dictionary key Is the field name of the database table , Dictionary value Is the value of the field .
The code defines add function ,add Function to add database table records . stay add The function uses try sentence , Used to catch exceptions that may occur when adding database table records , And output abnormal information , The exception information helps to locate the cause of the exception .
stay add Internal function , Defined SQL Query statement , And use for Loop binds all record data to be added to SQL In the sentence , call Cursor Of execute Method execution SQL sentence .
SQL After statement execution , Not submitted to the database , You also need to call Cursor Of commit Method to commit a database transaction , The database processes the submitted transactions in a unified way .
Update database table records
The update operation of database table records refers to updating the original records in the database table , The update operation is done by SQL Of UPDATE Statement complete ,Cursor object execute Method execution SQL UPDATE statement .
Case study 1: Update of data table records sql = "update shoper set brief = '%s' where id='0009'" % (" The computer 、 The server ")print("%d Record updated successfully " % (cursor.rowcount))
Modifying database table records requires the use of SQL Of UPDATE sentence , call Cursor Object's execute Method execution SQL sentence ,SQL After statement execution , Not submitted to the database , It just forms a database transaction , It needs to be called again Cursor Object's commit Method commit transaction , The database system performs committed transactions , The data table record is only updated .
Delete database table record
Deleting database table records refers to deleting qualified records in database tables , The deletion is done by SQL Of DELETE Statement complete .
Case study 1: Delete eligible database table records
sql = "delete from shoper where id='0010'"print("%d Record deleted successfully " % (cursor.rowcount))
Deleting database table records requires the use of SQL Of DELETE sentence ,DELETE In general, you should add WHERE Clause , Make conditional deletion , without WHERE Clause , All records of the database table will be deleted .