• 技术文章 >常见问题 >Python常见问题

    python更新不了数据库解决方法

     Ly Ly2020-06-15 10:36:46原创3079

    问题:

    在使用Python操作MySQL数据时,需要进行update操作,执行完后发现,更新并没有成功,但是进行查询操作就就可以成功。

    解决方法:

    如果要进行更新的操作,那么必须要在执行完sql后,加上connection.commit();

    如果只是查询的话,那就不用加了。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    sql_usr = 'aaa'

    sql_psw = 'aaa'

    sql_host = 'aaa'

    sql_port = 'aaa'

      

    def mysql1(sql):

        #打开数据库连接

        connection = pymysql.connect(host = sql_host,

                                     port = int(sql_port),

                                     user = sql_usr,

                                     password = sql_psw,

                                     charset = 'utf8')

        #使用cursor()方法创建一个游标对象cursor

        cursor = connection.cursor()

        cursor.execute(sql)#执行sql语句

        connection.commit()#执行update操作时需要写这个,否则就会更新不成功

        result = cursor.fetchone()

        #print(result)

        #result_cn = json.dumps(result,ensure_ascii=False)

        #print(result_cn)

        connection.close()

        return result

    更多Python知识,请关注:Python自学网!!

    专题推荐:python
    上一篇:python高并发怎么解决 下一篇:python和html哪个好

    相关文章推荐

    • python二级是全程上机考试么?• python二进制dat数据怎么转成txt文本• python高并发怎么解决

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网