MySQLdb - 什么时候提交和执行?

时间:2016-06-27 21:48:55

标签: python mysql database mysql-python

我在Python 2中使用MySQLdb,我有一个关于在数据库中执行查询的问题。假设我有一些连接form{ position: relative; overflow: hidden; padding-bottom: 80px; } label{ float: left; clear: both; margin-bottom: 20px; padding-right: 20px; } .fieldset-wrap{ overflow: hidden; float: left; clear: both; } .core{ float: left; clear: both; } .date{ margin-bottom: 30px; padding-bottom: 20px; border-bottom: 1px solid red; overflow: hidden; float: left; clear: both; } fieldset, button{ float: left; clear: both; margin-bottom: 20px; } .actions{ position: absolute; bottom: 0; left: 0; .button{ float: left; clear: both; } } .removeBtn{ display: none; },并使用<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="form" action=""> <label for="">Name<input type="text" /></label> <label for="">Age<input type="text" /></label> <div class="fieldset-wrap"> <div class="core"> <label for="">Car&nbsp;<input type="text" /></label> <label for="">Model&nbsp;<input type="text" /></label> </div> <div class="date"> <label for="">Date <input class="datepicker_multi" name="datepicker[]"/></label> </div> </div> <div class="actions"> <button class="addMoreBtn" type="button">Add more cars</button> <button class="removeBtn" type="button">remove</button> </div> </form> 实例化一个游标。以下哪项是提交数据库更改的正确方法?如果你能解释正确答案背后的理论,可以给予奖励积分:)

方法1:

con

方法2:

cur = con.cursor()

方法3:

try:
    cur.execute('command 1')
    con.commit()
    cur.execute('command 2')
    con.commit()
except MySQLdb.Error as e:
    con.rollback()

1 个答案:

答案 0 :(得分:0)

对于MySQLdb,我可能会这样做:

import contextlib

connection = get_connection_somehow()
with contextlib.closing(connection) as con:
    with con as cursor:
        cursor.execute(query1)
    with con as cursor:
        cursor.execute(query2)
    ...

当然,如果要执行多于一个或两个查询,请使用循环。

这里需要注意的一些事项:

  • 创建连接有点贵。
  • 创建游标非常便宜。
  • 当用作上下文管理器时,MySQLdb.Connection会为您提供一个新游标。