1. Connect MySQL
Download MySQL and download it on the website. All the way to install, set the account password.
Download the MySQL compilation environment, Navicat;
Create databases and tables in Navicat;
Create TableURLs (IDint not NULLAuto_increment,urlvarchar( +) not NULL, Contentvarchar(4000) not NULL, Created_timeTIMESTAMP DEFAULT Current_timestamp,Primary Key(ID))
Python link MySQL,
Install the library, pip install Mysqlclient.
Using Pyrhon to create a database in MySQL insert a data in the URLs table in Leon
Import Mysqldbconn= MySQLdb.connect (host='localhost' , user='root ', passwd='5407', db ='Leon'= conn.cursor () cur.execute ("INSERT into URLs (URL, content) VALUES (' www.baidu.com ', ' Content. ') " ) Cur.close () Conn.commit () Conn.close ( )
The results show:
host= ' localhost ', user= ' root ', passwd= ' 5407 ', db = ' Leon ', is the link name, username, password, database name
Delete operation:
Import mysqldb# Open database Connection db = MySQLdb.connect ("localhost", "testuser", "test123", "TESTDB") # Gets an operation cursor using the cursor () method Db.cursor () # SQL DELETE statement sql = "Delete from EMPLOYEE WHERE age > '%d '" "%" try: # Execute SQL statement cursor.execute (SQL)
# Commit Modify db.commit () except: # Rollback When an error occurs Db.rollback () # Close connection Db.close ()
Execution transactions
Transaction mechanisms ensure data consistency.
A transaction should have 4 properties: atomicity, consistency, isolation, persistence. These four properties are often called acid properties.
- Atomicity (atomicity). A transaction is an inseparable unit of work, and the operations included in the transaction are either done or not.
- Consistency (consistency). The transaction must be to change the database from one consistency state to another. Consistency is closely related to atomicity.
- Isolation (Isolation). Execution of one transaction cannot be disturbed by other transactions. That is, the operations inside a transaction and the data used are isolated from other transactions that are concurrently executing, and cannot interfere with each other concurrently.
- Persistence (durability). Persistence, also known as permanence (permanence), refers to the fact that once a transaction is committed, its changes to the data in the database should be permanent. The next operation or failure should not have any effect on it.
The transaction for Python DB API 2.0 provides two methods of commit or rollback.
Python crawler--Connect to database 1