Summary of pymysql common methods

1.pymysql main method

  • pymysql.connect() parameter description: (parameters that need to be added when connecting to the database)
  • host(str): MySQL server address
  • port(int): MySQL server port number
  • user(str): username
  • passwd(str): password
  • db(str): database name
  • charset(str): connection code
  • The methods supported by the connect() object:
  • cursor() uses the connection to create and return the cursor
  • commit() commit the current transaction
  • rollback() roll back the current transaction
  • close() close the connection
  • Methods supported by the cursor object:
  • execute(op) Execute a database query command
  • fetchone() Get the next row of the result set
  • fetchmany(size) Get the next few rows of the result set
  • fetchall() Get all rows in the result set
  • rowcount() returns the number of data or the number of affected rows
  • close() close the cursor object

2. Common operation explanation

Ready to work:

1. Import the library

import pymysql

2. Connect to the database

db = pymysql.connect(
				    host='localhost',
				    port=3306,
				    user='root',
				    password='123456',
				    database='【数据库名】',
				    charset='utf8'
    				) #mysql参数填自己配置的

3. Create a cursor

cursor = db.cursor()

Commonly used SQL statements

Insert data

  • method one:
sql = 'insert into 【表名】(【参数1】,【参数2】,【参数3】...) values(%s, %s, %s, %s...)'  # 注意是%s,不是s%
  • Way two:
sql = 'insert into 【表名】(【参数1】,【参数2】,【参数3】...) %(【数据1】,【数据2】,【数据3】...)' 

delete data

sql = 'delete from 【表名】 where 【查询参数】= %s'%(【数据】)

change the data

sql = 'update 【表名】 set 【参数】 = "%s" where 【查询参数】 = "%s"'%(【数值】,【数值】)

Query data

sql = 'select 【参数】 from 【表名】 where 【查询参数】= %s '%(【数据】)

Execute sql statement (can execute sql in a loop)

Parameter note: If the data to be executed contains quotation marks, use method two, because the sql statement itself is a string, and the quotation marks of multiple strings lead to confusion in the sql statement

  • Method one (corresponding to method one of inserting data):
cursor.execute(sql,([数据1],[数据2],))#注意元组最后有一个逗号
  • Method one (corresponding to method two of inserting data):
cursor.execute(sql)

Note: If you need to execute the function of the database itself, you only need to replace the data with a database function:
such as:now()

Close cursor

cursor.close()

Close the database (all operations are complete, close the database)

db.close()

Note: If you frequently connect to the database to prevent disconnection, you can use:db.ping(reconnect=True)

Guess you like

Origin blog.csdn.net/m0_50628560/article/details/109754676