以下代码运行没有任何错误,但记录未插入 table

Following code runs without any error but record is not inserted into the table

import pymysql


db_host = "localhost"
db_name = "mydatabse"
table_name = "Student"
db_user = "root"
db_pass = "745269"

query_insert = "INSERT INTO " + table_name + " (stu_id, stu_name) VALUES (%s, %s) "


class Student:
    id = 0
    name = ""

    def __init__(self, sid, name):
        self.id = sid
        self.name = name


def insert_record(rec):
    #print((rec.id, rec.name))
    con = pymysql.connect(host=db_host, user=db_user, password=db_pass, database=db_name)
    cur = con.cursor()
    cur.execute(query_insert, (rec.id, rec.name))
    #$cur.execute("INSERT INTO Student VALUES (%s, %s)", (3, 'Qwerty'))


r1 = Student(3, "Qwerty")
insert_record(r1)

我正在尝试使用 pymysql 模块向数据库中插入新行。我打算像 INSERT 一样全局定义所有查询。我想我遗漏了查询的一些格式,但到目前为止还无法指出。提前感谢任何帮助。

根据https://pymysql.readthedocs.io/en/latest/user/examples.html、"connection is not autocommit by default. So you must commit to save your changes."

这将导致:

import pymysql


db_host = "localhost"
db_name = "mydatabse"
table_name = "Student"
db_user = "root"
db_pass = "745269"

query_insert = "INSERT INTO " + table_name + " (stu_id, stu_name) VALUES (%s, %s) "


class Student:
    id = 0
    name = ""

    def __init__(self, sid, name):
        self.id = sid
        self.name = name


def insert_record(rec):
    #print((rec.id, rec.name))
    con = pymysql.connect(host=db_host, user=db_user, password=db_pass, database=db_name)
    cur = con.cursor()
    cur.execute(query_insert, (rec.id, rec.name))
    #$cur.execute("INSERT INTO Student VALUES (%s, %s)", (3, 'Qwerty'))
    con.commit()  # Added this commit call


r1 = Student(3, "Qwerty")
insert_record(r1)