Python3 operates MySQL8 database

The software used in this chapter is: Software: pycharm Professional Edition Database: MySQL 8.0.28 

pycharm plugin: pymysql

This chapter is divided into theory and practice, please prepare the software plug-in by yourself  

If beginners are struggling to read theoretically, they can compare it with practical operations, and they can almost understand it with a little foundation.

basic theory

       The data connection object mainly provides methods for obtaining database cursor objects and committing/rolling back transactions, as well as closing the database

1. Get the connection object

        To connect to the database, you need to use the pymysql.connect() function, which has multiple parameters, and which parameters to use depends on the type of database.

        Connect() function common parameter description

parameter illustrate
dsn The name of the data source, given the parameter to indicate the database dependency
user username
password user password
host hostname or IP address
database Name database

 2. The method of connecting objects

        The connect() function returns a connection object, which represents the current session state with the database.

Methods and descriptions supported by connection objects 

method illustrate
close() close database connection
commit() commit transaction
rollback() rollback transaction
cursor() Get the cursor object, operate the database, such as executing DML statement operations, calling stored procedures, etc.

3. Cursor object

        The cursor object represents the cursor in the database and is used to indicate the context of the fetching data operation. It mainly provides methods for executing SQL statements, calling stored procedures, and obtaining query results.

        The cursor object can be obtained by using the cursor method of the connection object.

Cursor Object Methods/Properties and Statements

method/property illustrate
callproc(procname,[parameters]) Calling stored procedures requires the support of the database
close() close the current cursor
execute(operation,[parameters]) Execute database operations, SQL statements or database command execution
executemany(operation,sql_of_params) For batch operations, such as batch updates
fetchone() Get a single data result
fetchmany() Get the specified number of records
fetchall() Get multiple pieces of data
nextset() Skip to the next available result
arraysize Specifies the number of rows to fetch using the fetchmany method, the default is 1
setinputsizes(*args) Sets the size of the memory area allocated when calling the execute*() method
setoutputsizes(*args) Set the column buffer size, especially useful for large data including LONGS and BLOBS

Practical

1. Use pymysql to connect to the MySQL database

Format:

import pymysql as m

# 打开数据库进行链接 host 主机名或ip  user:用户名 password:密码 database:数据库名称
db = m.connect(host="localhost", user="user", password="User.123", database="Practice")
# 使用cursor方法创建一个游标对象
cursor = db.cursor()
# 使用 execute 方法执行sql 查询
cursor.execute("select * from app_handoverinfo;")
# 使用 fetchall 方法获取多条数据  单条数据用 fetchone()
data = cursor.fetchall()
# 输出数据
print(data)
db.close() # 关闭数据库  

 #Remember to close the database after use
#Reason: In python programming, you can use pymysql for database connection and addition, deletion, modification and query operations, but every time you connect to mysql request, you request access independently, which is a waste of resources, and the number of visits reaches a certain level When the number is large, it will have a greater impact on the performance of mysql.

2. Use pymysql to create a data table

import pymysql as m

# 打开数据库进行链接 host 主机名或ip  user:用户名 password:密码 database:数据库名称
db = m.connect(host="localhost", user="user", password="User.123", database="Practice")
# 使用cursor方法创建一个游标对象
cursor = db.cursor()
#cursor.execute("drop table test1;") #如果库中有该表则删除该表重新创建

# 使用sql语句去创建一个数据表
sql = """CREATE TABLE test1(
id INT NOT NULL AUTO_INCREMENT COMMENT 'ID',
sno INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '学号',
sName VARCHAR(20) NOT NULL COMMENT '姓名',
sex ENUM('男','女','保密') NOT NULL DEFAULT '保密' COMMENT '性别',
age TINYINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '年龄',
Time TIMESTAMP NOT NULL DEFAULT NOW() COMMENT '入学时间',
-- Time DATE NOT NULL DEFAULT '1000-01-01' COMMENT '入学时间', # 注意设定默认值的时候 NOW 以及其他函数不管用
PRIMARY KEY(id),
INDEX(sName),
UNIQUE(sno)  # 写法误区 切勿在最后一行的时候  加逗号 !
)ENGINE INNODB CHARSET utf8mb4 COLLATE utf8mb4_bin AUTO_INCREMENT=10;"""  # 注意用三个引号引起来不然会报错

# 使用 execute 方法执行sql
cursor.execute(sql)
cursor.execute("show create table test1;")
# 使用 fetchall 方法获取多条数据  单条数据用 fetchone()
data = cursor.fetchall()
# 输出数据
print(data)  
db.close()
# 关闭数据库

 3. Operate MySQL data table

Batch Insert Data Method

# -*- coding: UTF-8 -*-

import pymysql as m

# 打开数据库进行链接 host 主机名或ip  user:用户名 password:密码 database:数据库名称
db = m.connect(host="localhost", user="user", password="User.123", database="Practice")
# 使用cursor方法创建一个游标对象
cursor = db.cursor()
# 数据列表
data = [(1, "张三", "男", "25",),
        (2, "李四", "女", "20"),
        (3, "王五", "保密", "23")
        ]

try:
    # 执行SQL语句 插入多条数据
    cursor.executemany("insert into test1(sno,sName,sex,age) values(%s,%s,%s,%s);", data)
    # 提交数据
    db.commit()
    print("成功")
except:
    # 发生错误回滚
    db.rollback()
    print("失败")
cursor.execute("select * from test1;")
select = cursor.fetchall()
# 输出数据
print(select)
db.close()
# 关闭数据库

Guess you like

Origin blog.csdn.net/weixin_58279299/article/details/126286897