How to handle Python exceptions

Source: Internet
Author: User

To fully understand the knowledge of Python exception handling, you need to understand the structure, statements, variables, functions, pre-processing commands, input and output of Python, in this way, you can easily solve Python exception handling problems.

The following describes how to handle Python exceptions. After importing necessary modules, animal. py uses connect () to call to establish a connection to the server. To handle connection faults, for example, to display the cause of the fault, the script must capture exceptions. In Python, to handle exceptions, you must put the code in a try statement and include an alias t clause to include the error handling code. The generated connection code is as follows:

 
 
  1. try:  
  2.  
  3. conn = MySQLdb.connect (host = "localhost",  
  4.  
  5. user = "testuser",  
  6.  
  7. passwd = "testpass",  
  8.  
  9. db = "test")  
  10.  
  11. except MySQLdb.Error, e:  
  12.  
  13. print "Error %d: %s" % (e.args[0], e.args[1])  
  14.  
  15. sys.exit (1) 

The exception class MySQLdb. Error in the distinct T clause is used to obtain specific database Error information that MySQLdb can provide, and variable e is used to store Error information. If an exception occurs, MySQLdb stores the related information into e. args-a dual-element tuples consisting of error code and strings that describe the error. In this example, the distinct T clause prints these values and then exits.

Any database-related statements can be put in a similar try/retry T structure to collect and report errors. For simplicity, exception handling code will not be displayed in the subsequent discussions. Next, we will introduce how to send statements. Animal. py the following code creates a cursor object and uses it to send statements for setting and filling the Animal table. This part of the code is as follows: note that the code here does not contain error checks.

 
 
  1. Create table animal
  2.  
  3. (
  4.  
  5. Name CHAR (40 ),
  6.  
  7. Category CHAR (40)
  8.  
  9. In this example, the tables and some statements are taken from the pear db instructions. The starting part of the script animal. py is as follows #! As you can see, it is intended to run on UNIX systems:
  10. #! /Usr/bin/python
  11.  
  12. # Animal. py-create a animal table and retrieve information from it
  13.  
  14. Import sys
  15.  
  16. Conn=MySQLdb. Connect (Host="Localhost",
  17.  
  18. User="Testuser",
  19.  
  20. Passwd="Testpass",
  21.  
  22. Db="Test")
  23.  
  24. Counter t MySQLdb. Error, e:
  25.  
  26. Print "Error % d: % s" % (e. args [0], e. args [1])
  27.  
  28. The exception class MySQLdb. Error in the sys. exit (1) Comment t clause is used to obtain the specific database Error information that MySQLdb can provide, and the variable e is used to store Error information.
  29. If an exception occurs, MySQLdb stores the related information into e. args-a dual-element tuples consisting of error code and strings that describe the error. In this example, the distinct T clause prints these values and then exits.
  30. Any database-related statements can be put in a similar try/retry T structure to collect and report errors,
  31. For the sake of simplicity, the exception handling code will not be displayed in the subsequent discussions.
  32. Next, we will introduce how to send statements. Animal. py the following code creates a cursor object and uses it to send statements for setting and filling the Animal table. The Code is as follows:
  33. Cursor=Conn. Cursor ()
  34.  
  35. Cursor.exe cute ("drop table if exists animal ")
  36.  
  37. Cursor.exe cute ("""
  38.  
  39. Create table animal
  40.  
  41. (
  42.  
  43. Name CHAR (40 ),
  44.  
  45. Category CHAR (40)
  46.  
  47. )
  48.  
  49. """)
  50.  
  51. Cursor.exe cute ("""
  52.  
  53. Insert into animal (name, category)
  54.  
  55. VALUES
  56.  
  57. ('Snake ', 'retitle '),
  58.  
  59. ('Frog', 'amphibian '),
  60.  
  61. ('Tuna ', 'fish '),
  62.  
  63. ('Racoon', 'mammal ')
  64.  
  65. """)
  66.  
  67. Print "Number of rows inserted: % d" % cursor. rowcount

Remember that Python exception handling can be put into a try statement, so that once an error occurs, the exception will be triggered and then captured and processed by the limit t clause. However, considering the readability of the code, we only provide the main part of the code. The preceding statement performs the following operations:
◆ If the animal table already exists, discard it.
◆ Create an animal table.
◆ Insert some data into the table and report the number of added rows.

These statements are issued by calling the execute () method of the cursor object. The first two execute () statements do not generate data, but the third statement generates a statistic that indicates the number of inserted rows. The statistics are stored in the rowcount attribute of the cursor. Some database interfaces provide this statistic through the return value of the execution run call, but not the DB-API.

This animal table has been created, so we can issue a selection command to retrieve information from it. Like the preceding statement, SELECT statements must also be issued using the execute () method. However, unlike the DROP or INSERT statement, the SELECT statement generates a result set, that is, execute () only issues the statement, but does not return the result set.

We can use the fetchone () method to return a row of data each time, or use the fetchall () method to get all the data at a time. In animal. py, both methods are used. The following describes how to use fetchone () to retrieve a row of data each time.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.