使用场景如下:
有2条插入语句需要在python执行,如下:

dql0 = "INSERT INTO shopref (goodsName,prcutMode,shardingCode) VALUES ('新牌便民伞',NULL,'21000');"

dql1 = "INSERT INTO good (sellIntro,stockMode) VALUES (1,10);"

# 执行数据库
Sql().execute(dql0)

Sql().execute(dql1)

数据库进行了如下封装:

class Sql:

    def __init__(self, host="", port=3306,user="",password="", database="",):
        self.db = pymysql.connect(
            host=host,
            port=port,
            user=user,
            password=password,
            database=database
            )
        self.__cursor = self.db.cursor()

    def execute(self,dql):
        """执行数据库语句"""
        self.__cursor.execute(dql)
        return self

运行完数据库操作语句后,发现数据库中并没有新增数据。

经过不断地查找原因,发现Python连接器不会auto commit by default。还需要在执行语句之后commit数据。插入或更新数据后调用此方法很重要。

解决方法一:

class Sql:

    def __init__(self, host="", port=3306,user="",password="", database="",):
        self.db = pymysql.connect(
            host=host,
            port=port,
            user=user,
            password=password,
            database=database
            )
        self.__cursor = self.db.cursor()
    def execute(self,dql):
        """执行数据库查询语句"""
        self.__cursor.execute(dql)
        return self
    def execute_insert(self,dql):
       """执行数据库插入语句"""
        self.__cursor.execute(dql)
        self.db.commit()
        return self

代码中的数据库操作语句改为:

Sql().execute_insert(dql0)

Sql().execute_insert(dql1)

解决方法二:

在连接信息中 增加autocommit=True

self.db = pymysql.connect(
            host=host,
            port=port,
            user=user,
            password=password,
            database=database,
            autocommit=True
            )

代码中的数据库操作语句不用改,再次运行后,在数据库中可以查到数据。

注意点:在执行插入语句时,需要在sql语句中带插入数据库表的ColumnList。

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐