Catalog
Following "Python Learning Road Five":
error handling
In the process of running the program, if there is an error, you can agree in advance to return an error code, so that you can know whether there is an error, and the cause of the error. It is very common to return error codes in calls provided by the operating system. For example, the function open() that opens the file, returns the file descriptor (that is, an integer) when it succeeds, and returns - 1 when it goes wrong.
It is inconvenient to use error codes to indicate whether there is an error, because the normal result that the function itself should return is mixed with the error codes, which makes the caller have to use a lot of code to judge whether there is an error:
Once an error occurs, it must be reported at the first level until a function can handle the error (for example, output an error message to the user). So high-level languages usually have built-in error handling mechanisms such as try...except...finally... and Python is no exception.
try
Let's take an example of try's mechanism:
When you think that some code may make mistakes, you can use try to run this code. If you make a mistake, the subsequent code will not continue to execute, but jump directly to the error handling code, that is, except statement block. After except is executed, if there is a final statement block, the final statement block will be executed. Execution is complete.
Document Reading and Writing
Reading and writing files is the most common IO operation. Python has built-in functions for reading and writing files, which are compatible with C.
Before reading and writing files, we must understand that the function of reading and writing files on disk is provided by operating system. Modern operating system does not allow ordinary programs to operate disk directly. So, reading and writing files is to request operating system to open a file object (usually called file descriptor), and then, through operation. The interface provided by the system reads data (reads files) from the file object or writes data to the file object (writes files).
read file
To open a file object in the mode of reading a file, use Python's built-in open() function to pass in the file name and identifier:
>>> f=open("\a.txt","r")
The identifier'r'indicates reading, so that we successfully open a file.
If the file does not exist, the open() function throws an IOError error and gives the error code and detailed information to tell you that the file does not exist:
>>> f=open("/a.txt") Traceback (most recent call last): File "<pyshell#28>", line 1, in <module> f=open("/a.txt") FileNotFoundError: [Errno 2] No such file or directory: '/a.txt'
If the file opens successfully, then the entire content of the file can be read at a time by calling read() method. Python reads the content into memory, which is represented by a str object:
>>> f.reat() "Hello,World!"
The last step is to close the file by calling the close() method. Files must be closed after they have been used, because the file object will occupy the resources of the operating system, and the number of files that the operating system can open at the same time is limited:
f.close()
Since IOError may occur when a file is read or written, the following f.close() will not be invoked once an error occurs. Therefore, in order to ensure that the file can be closed correctly, whether there is an error or not, we can use try... final to achieve:
>>> try : f = open("/a.txt","r") print(f.read()) finally : if f : f.close()
But it's too cumbersome to write like this every time, so Python introduces the with statement to automatically call the close() method for us:
>>> with open("/a.txt","r") as f : print(f.read())
This is the same as try... final, but the code is better and concise, and there is no need to call the f.close() method.
Calling read() reads all the contents of the file at one time. If the file has 10G, the memory will explode. So, to be safe, you can call read(size) method repeatedly and read up to size bytes at a time. In addition, calling readline() reads one line at a time, and calling readlines() reads all the contents at a time and returns the list by line. Therefore, it is necessary to decide how to invoke it. If the file is small, read() is the most convenient to read at one time; if the file size cannot be determined, it is safer to call read(size) repeatedly; if it is a configuration file, it is the most convenient to call readlines():
>>> for line in f.readlines(): print(line.strip())
Writing Documents
Writing and reading files are the same. The only difference is that when the open() function is called, the incoming identifier'w'or'wb' means writing a text file or writing a binary file:
>>> f = open("/a.txt","w") >>> f.write("Hello,world") >>> f.close()
You can call write() repeatedly to write to a file, but you must call f.close() to close the file. When we write files, the operating system usually does not write data to disk immediately, but to memory cache, write slowly when idle. Only when the close() method is invoked can the operating system ensure that all data not written is written to disk. The consequence of forgetting to call close() is that data may only be written to disk, leaving the rest missing. So, use the with statement to insure:
>>> with open("/a.txt","w") as f: f.write("Hello,Jerry!")
To write a specific encoding text file, pass in the encoding parameter to the open() function, and automatically convert the string into the specified encoding. When writing to a file in'w'mode, if the file already exists, it will be overwritten directly (equivalent to writing a new file after deletion). What if we want to add it to the end of the document? You can pass in'a'and write in append mode.
PyMysql
Query operation
import pymysql # Import pymysql # Open database connection db = pymysql.connect(host="localhost", user="root",password="123456", db="test", port=3307) # Using cursor() method to get operation cursor cur = db.cursor() # 1. Query operation # Write sql query statement user corresponding to my table name sql = "select * from user" try: cur.execute(sql) # Execute sql statements results = cur.fetchall() # Get all records of the query print("id", "name", "password") # Ergodic results for row in results: id = row[0] name = row[1] password = row[2] print(id, name, password) except Exception as e: raise e finally: db.close() # Close the connection
Insert operation
import pymysql # 2. Insertion operation db = pymysql.connect(host="localhost", user="root",password="123456", db="test", port=3307) # Using cursor() method to get operation cursor cur = db.cursor() sql_insert = """insert into user(id,username,password) values(4,'liu','1234')""" try: cur.execute(sql_insert) # Submission db.commit() except Exception as e: # Error rollback db.rollback() finally: db.close()
update operation
import pymysql # 3. Update operation db = pymysql.connect(host="localhost", user="root",password="123456", db="test", port=3307) # Using cursor() method to get operation cursor cur = db.cursor() sql_update = "update user set username = '%s' where id = %d" try: cur.execute(sql_update % ("xiongda", 3)) # Passing parameters like sql statements # Submission db.commit() except Exception as e: # Error rollback db.rollback() finally: db.close()
Delete operation
import pymysql # 4. Delete operation db = pymysql.connect(host="localhost", user="root",password="123456", db="test", port=3307) # Using cursor() method to get operation cursor cur = db.cursor() sql_delete = "delete from user where id = %d" try: cur.execute(sql_delete % (3)) # Passing parameters like sql statements # Submission db.commit() except Exception as e: # Error rollback db.rollback() finally: db.close()
(Write at the end: Welcome to make corrections)