Python DB-API

1. DB-API

1.1. Python's DB-API implements interfaces for most databases. After using it to connect to each database, you can operate each database in the same way.

1.2. The usage process of Python DB-API:

  • Introduce API module
  • Get a connection to the database
  • Execute sql statements and stored procedures
  • close database connection

1.3, Python operation mysql

Python3 does not support MySQLdb anymore, and uses pymysql. The functions of these two modules are exactly the same, while 2.x uses the MySQLdb module

1.4. Example:

 

import pymysql 

class TestMysql(object):
def __init__(self): #The function of the constructor of this class is to define the connection. After encapsulation, there is no need to reconnect each time it is called, which improves the resource utilization of the system and the efficiency of code execution
self.dbConfig = {
"host": "192.168.48.136",
"port": 3306,
"user": "xiang",
"passwd": "xiang",
"db": "test"
}
conn = pymysql.connect(**self .dbConfig)
self.a = conn

def select(self):
print("select")

def update(self):
print("update")


if __name__ == '__main__':
conn = TestMysql()

 

Second, Mysql things

2.1. Generally speaking, things must meet four conditions (ACID): Atomicity (atomicity), Consistency (stability), Isolation (isolation), Durability (reliability)

  • The atomicity of things : a set of things that either succeeds or withdraws
  • Stability : there are illegal data (foreign key constraints and the like), things are withdrawn
  • Isolation : Things run independently, the result of processing one thing affects other things, then other things will be withdrawn, things are 100% isolated, and speed needs to be sacrificed
  • Reliability : After the software and hardware crash, the InnoDB data table driver will use the log file to reconstruct and modify, reliability and high speed cannot have both, the innodb flush log at trx commit option determines when to save things in the log

2.2, MySQL common operations:

  • Create users and authorize : grant all on library name. Table name to 'user1' identified by 'passwd';
  • Check the authorization status : show grants;
  • View the number of rows in the table : select count(*) from mysql.user;
  • View the contents of the table : select * from mysql.db;
  • 查询表相关:select db from mysql.db; select db,user from mysql.db; select * from mysql.db where host like '192.168.%';
  • 插入表数据:insert into db1.t1 values (1, 'abc');
  • 更新表数据:update db1.t1 set name='aaa' where id=1;
  • 清空表内容:truncate table db1.t1;
  • 删除表:drop table db1.t1;
  • 删除库:drop database db1;

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325540725&siteId=291194637