Python self-study planning, how to learn programming step by step

Learning blog 2020-11-14 01:07:18
python self-study self study planning

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
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 . Recommend a good place to write 300 word 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 .

本文为[Learning blog]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database