zoukankan      html  css  js  c++  java
  • python数据查询操作之 一场缺少db.commit()引发的血案……

    最近大作业用到了python操作数据库的内容。涉及的库是pymmysql,我就不详细介绍这个库的操作了,直接奔入主题--->开整



     背景:

           涉及程序中一个实时查看数据表中state字段==1的功能,我把这个功能单独择出来写成了下面的代码: 

     1 # -*- coding=utf-8 -*-
     2 import pymysql
     3 config={
     4     "host":"127.0.0.1",
     5     "user":"root",
     6     "password":"root",
     7     "database":"Person"
     8 }
     9 db = pymysql.connect(**config)
    10 cursor=db.cursor()
    11 while True:
    12     a=input("Input something interesting:")
    13     sql = "select username from client where state=1"
    14     try:
    15         cursor.execute(sql) 
    16         result=cursor.fetchall()
    17     except:
    18         db.rollback()
    19     print(result)
    20 cursor.close()
    21 db.close()

        

      这是数据库Person的数据表client内容,关键在最后的state内容

      执行这个代码:python3 testdb.py 出现下面效果:

           

       现在看起来是正确的,但是现在不关闭这个python程序,使其阻塞,同时更改数据库内容

      

      我把Iverson这条数据的状态state也设为1,然后跑去python继续执行看有什么结果

      

      发现,虽然直接操控数据库成功,代码查询还是以前的结果没有变化……



      解决方案:

      做了很多次修改,把cursor的定义和关闭都放到while循环里面都没变化还是存在问题;

      最后才发现我是少了关键的一行代码---db.commit(),添加后的代码

      

     1 import pymysql
     2 config={
     3     "host":"127.0.0.1",
     4     "user":"root",
     5     "password":"root",
     6     "database":"Person"
     7 }
     8 db = pymysql.connect(**config)
     9 cursor=db.cursor()
    10 while True:
    11     a=input("Input something interesting:")
    12     sql = "select username from client where state=1"
    13     try:
    14         cursor.execute(sql) 
    15         db.commit()
    16         result=cursor.fetchall()
    17     except:
    18         db.rollback()
    19     print(result)
    20 cursor.close()
    21 db.close()

      执行下:

      初始状态

      更改数据库:

      

      再次测试代码:

       

      这次终于没问题了……心累



          总结:

      第一次看python关于mysql的操作的是菜鸟教程,关于commit方法第一感觉是这个方法只用来提交“数据”,比如插入数据、更新数据需要在execute()后面跟上一个commit();现在看来,commit()方法需要跟在增(insert)、删(delete)、改(update)、查(select)的任何execute()语句后面。commit是把查询语句提交到数据库内,而不只是要向数据库提交增、添的数据。

      就这样吧……

  • 相关阅读:
    C# MVC模式设置404&500
    jQuery实现滚动条滚动到子元素位置(方便定位)
    Oracle数据库的导出导入
    Oracle之clob字段不能union的问题
    div中内容垂直居中的方法小结
    C#实现Oracle数据库插入clob字段类型数据
    C_结构体_笔记
    Practice_17_01_ABC
    Practice_17_01_GID
    【转】 vim显示行号、语法高亮、自动缩进的设置
  • 原文地址:https://www.cnblogs.com/Higgerw/p/9922653.html
Copyright © 2011-2022 走看看