Python Mysql
Contents
1. Application architecture
Client –> Business logic layer –> Data access layer –> Database
2. Python DB API
Python application (including SQL) –> Python DB API (unified and standardized interface for accessing database MySQLdb) –> MySQL/Oracle/SQLServer and other databases
Database connection object: connection
Database interaction object: cursor
Database exception class: exceptions
3. Access database process:
Create connection object connection –> Get interactive object cursor –> Execute query/execute command/get data/process data, etc. –> Close cursor –> Close connection
4. Database connection object: connection
Establish a network connection between the Python client and the database
Creation method: MySQLdb.Connect()
Parameters:
host database server address
port port number, numeric type
user username
passwd password
db database name
charset encoding format, utf8
- Method:
cursor() gets the interactive object (cursor)
commit() commits the current transaction
rollback() rolls back the current transaction
close() closes the connection
5. Database interaction object (cursor) cursor: used to execute queries and obtain results
- Method:
execute(op [, args] ) executes SQL and obtains the results from the database to the client. There is a local buffer.
fetch*() method: move the pointer rownumber and return data.
fetchone() gets the next row of the result set
fetchmany(size) gets the next few rows of the result set
fetchall() gets all the remaining rows in the result set
- close() closes the cursor object
- Attribute: rowcount The number of rows of data returned by the latest execution or the number of affected rows.
6. Affairs
A program execution unit that accesses and updates the database, which can contain multiple SQL statements or command operations.
The engine must be set to INNODB.
Features:
Atomicity: All operations included in the transaction are either not performed or are performed.
Consistency: A transaction must change the database from a consistent state to another consistent state.
Isolation: The execution of a transaction cannot be interfered with by other transactions.
Durability: Once a transaction is committed, its changes to the database are permanent.
- Use transactions:
Turn off automatic commit: set conn.autocommit(False);
End the transaction normally: conn.commit();
Abnormal end of transaction: conn.rollback().