在python中使用带有“WITH"的sqlite3;关键词 [英] using sqlite3 in python with "WITH" keyword

查看:65
本文介绍了在python中使用带有“WITH"的sqlite3;关键词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个教程,遇到了一种处理与 sqlite3 连接的方法,然后我研究了 WITH 关键字,发现它是一种替代尝试,除了,finally 做事的方式

I was doing a tutorial and came across a way to handle connections with sqlite3, Then I studied about the WITH keyword and found out that it is an alternative to try,except,finally way of doing things

据说在文件处理的情况下,'WITH'会自动处理文件的关闭,我认为与zetcode教程中所说的连接类似:-

It was said that in case of file-handling, 'WITH' automatically handles closing of files and I thought similar with the connection as said in zetcode tutorial:-

"使用with关键字,Python解释器自动释放资源.它还提供错误处理." http://zetcode.com/db/sqlitepythontutorial/

"With the with keyword, the Python interpreter automatically releases the resources. It also provides error handling." http://zetcode.com/db/sqlitepythontutorial/

所以我认为使用这种处理方式会很好,但我无法弄清楚为什么这两个(内部作用域和外部作用域)语句都有效?WITH 不应该释放连接吗?

so I thought it would be good to use this way of handling things, but I couldn't figure out why both (inner scope and outer scope) statements work? shouldn't the WITH release the connection?

import sqlite3

con = sqlite3.connect('test.db')

with con:    
    cur = con.cursor()    

    cur.execute('SELECT 1,SQLITE_VERSION()')
    data = cur.fetchone()   
    print data        

cur.execute('SELECT 2,SQLITE_VERSION()')
data = cur.fetchone()
print data

哪个输出

(1, u'3.6.21')
(2, u'3.6.21')

我不知道 WITH 在这里到底在做什么(或一般做什么),所以,如果你愿意详细说明在这种情况下 WITH 而不是 TRY CATCH 的使用.

I don't know what exactly the WITH is doing here(or does in general), so, if you will please elaborate on the use of WITH over TRY CATCH in this context.

应该在每次查询时打开和关闭连接吗?(我在每次使用参数调用的函数中制定查询)这是一个好习惯吗?

And should the connections be opened and closed on each query? (I am formulating queries inside a function which I call each time with an argument) Would it be a good practice?

推荐答案

来自文档:http://docs.python.org/2/library/sqlite3.html#using-the-connection-as-a-context-manager

Connection 对象可以用作自动提交或回滚事务的上下文管理器.发生异常时,事务回滚;否则,事务被提交:

Connection objects can be used as context managers that automatically commit or rollback transactions. In the event of an exception, the transaction is rolled back; otherwise, the transaction is committed:

因此,上下文管理器不会释放连接,而是确保在发生任何异常时回滚连接上发生的任何事务,或以其他方式提交...code>DELETE、UPDATEINSERT 查询为例.

So, the context manager doesn't release the connection, instead, it ensures that any transactions occurring on the connection are rolled back if any exception occurs, or committed otherwise... Useful for DELETE, UPDATE and INSERT queries for instance.

这篇关于在python中使用带有“WITH"的sqlite3;关键词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆