Die PyMySQL-Operation von MySQL

PyMysql ist eine in reinem Python implementierte MySQL-Clientbibliothek, die die Kompatibilität mit Python3 unterstützt und als Ersatz für MySQLdb verwendet wird

Abfragevorgang

Schreiben Sie im Voraus, um die entsprechenden Tabellen und Daten in MySQL vorzubereiten

CREATE DATABASE IF NOT EXISTS mydb17_pymysql;

USE mydb17_pymysql;

CREATE TABLE IF NOT EXISTS student(
	sid INT PRIMARY KEY auto_increment,
	sname VARCHAR(20),
	age INT
);

INSERT INTO student VALUES(NULL,'宋江',30),(NULL,'武松',28),(NULL,'林冲',26);

Anfragen

import pymysql

# 获取mysql连接
conn = pymysql.connect(host='localhost', port=3306, user='root', password=, database='mydb17_pymysql')

# 获取游标
cursor = conn.cursor()

# 执行SQL语句 返回值就是SQL语句在执行过程中影响的行数

sql = "select * from student;"

row_count = cursor.execute(sql)
print("SQL语句执行影响的行数%d"%row_count)

# 取出结果集中一行,返回的结果是一行
# print(cursor.fetchone())

# 取出结果集中的所有数据,返回一行数据
for line in cursor.fetchall():
    print(line)

# 关闭游标
cursor.close()

CRUD-Operation

import pymysql

# 获取mysql连接
conn = pymysql.connect(host='localhost', port=3306, user='root', password=, database='mydb17_pymysql')

# 获取游标
cursor = conn.cursor()

# 执行SQL语句 返回值就是SQL语句在执行过程中影响的行数

sql = "select * from student;"

row_count = cursor.execute(sql)
print("SQL语句执行影响的行数%d"%row_count)

# 取出结果集中一行,返回的结果是一行
# print(cursor.fetchone())

# 取出结果集中的所有数据,返回一行数据
for line in cursor.fetchall():
    print(line)

# 关闭游标
cursor.close()

Ich denke du magst

Origin blog.csdn.net/JAX_fire/article/details/125828938
Empfohlen
Rangfolge