我今天刚与一些同事就python的db-api fetchone vs fetchmany vs fetchall进行了讨论.
我确定每个用例的用例取决于我正在使用的db-api的实现,但一般来说fetchone vs fetchmany vs fetchall的用例是什么?
换句话说是以下等价物?或者其中一个比其他的更受欢迎?如果是这样的话?
cursor.execute("SELECT id, name FROM `table`")
for i in xrange(cursor.rowcount):
id, name = cursor.fetchone()
print id, name
cursor.execute("SELECT id, name FROM `table`")
result = cursor.fetchmany()
while result:
for id, name in result:
print id, name
result = cursor.fetchmany()
cursor.execute("SELECT id, name FROM `table`")
for id, name in cursor.fetchall():
print id, name
Run Code Online (Sandbox Code Playgroud) 我有一个不返回命中的sql语句.例如,'select * from TAB where 1 = 2'.
我想查看返回的行数,
cursor.execute(query_sql)
rs = cursor.fetchall()
Run Code Online (Sandbox Code Playgroud)
在这里我得到了异常:"(0,'没有结果集')"
如何预先设置此异常,检查结果集是否为空?
我正在尝试将一些代码移植到使用sqlite数据库的Python,而我正试图让事务工作,我真的很困惑.我真的很困惑; 我在其他语言中经常使用sqlite,因为它很棒,但我根本无法弄清楚这里有什么问题.
这是我的测试数据库的模式(将被输入sqlite3命令行工具).
BEGIN TRANSACTION;
CREATE TABLE test (i integer);
INSERT INTO "test" VALUES(99);
COMMIT;
Run Code Online (Sandbox Code Playgroud)
这是一个测试程序.
import sqlite3
sql = sqlite3.connect("test.db")
with sql:
c = sql.cursor()
c.executescript("""
update test set i = 1;
fnord;
update test set i = 0;
""")
Run Code Online (Sandbox Code Playgroud)
你可能会注意到故意的错误.执行更新后,这会导致SQL脚本在第二行失败.
根据文档,该with sql语句应该围绕内容建立一个隐式事务,只有在块成功时才会提交.但是,当我运行它时,我得到了预期的SQL错误...但是i的值从99设置为1.我希望它保持在99,因为第一次更新应该回滚.
这是另一个测试程序,它显式调用commit()和rollback().
import sqlite3
sql = sqlite3.connect("test.db")
try:
c = sql.cursor()
c.executescript("""
update test set i = 1;
fnord;
update test set i = 0;
""")
sql.commit()
except sql.Error:
print("failed!")
sql.rollback() …Run Code Online (Sandbox Code Playgroud) psycopg2是否有一个函数来转义Postgres 的LIKE操作数的值?
例如,我可能想要匹配以字符串"20%of all"开头的字符串,所以我想写这样的东西:
sql = '... WHERE ... LIKE %(myvalue)s'
cursor.fetchall(sql, { 'myvalue': escape_sql_like('20% of all') + '%' }
Run Code Online (Sandbox Code Playgroud)
我可以在这里插入一个现有的escape_sql_like函数吗?
(类似的问题如何显式引用字符串值(Python DB API/Psycopg2),但我找不到答案.)
我很困惑为什么python需要游标对象.我知道jdbc,那里的数据库连接非常直观但是在python中我与游标对象混淆了.另外,我怀疑在资源释放方面cursor.close()和connection.close()函数之间的区别是什么.
我试图使用python的db-api汇编以下SQL语句:
SELECT x FROM myTable WHERE x LIKE 'BEGINNING_OF_STRING%';
Run Code Online (Sandbox Code Playgroud)
其中BEGINNING_OF_STRING应该是一个python var,可以通过DB-API安全地填充.我试过了
beginningOfString = 'abc'
cursor.execute('SELECT x FROM myTable WHERE x LIKE '%s%', beginningOfString)
cursor.execute('SELECT x FROM myTable WHERE x LIKE '%s%%', beginningOfString)
Run Code Online (Sandbox Code Playgroud)
我没有想法; 这样做的正确方法是什么?
我在Python中有一个JSON对象.我正在使用Python DB-API和SimpleJson.我试图将json插入MySQL表.
在我收到错误的那一刻,我相信这是由于JSON对象中的单引号''.
如何使用Python将我的JSON对象插入MySQL?
这是我收到的错误消息:
error: uncaptured python exception, closing channel
<twitstream.twitasync.TwitterStreamPOST connected at
0x7ff68f91d7e8> (<class '_mysql_exceptions.ProgrammingError'>:
(1064, "You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for
the right syntax to use near ''favorited': '0',
'in_reply_to_user_id': '52063869', 'contributors':
'NULL', 'tr' at line 1")
[/usr/lib/python2.5/asyncore.py|read|68]
[/usr/lib/python2.5/asyncore.py|handle_read_event|390]
[/usr/lib/python2.5/asynchat.py|handle_read|137]
[/usr/lib/python2.5/site-packages/twitstream-0.1-py2.5.egg/
twitstream/twitasync.py|found_terminator|55] [twitter.py|callback|26]
[build/bdist.linux-x86_64/egg/MySQLdb/cursors.py|execute|166]
[build/bdist.linux-x86_64/egg/MySQLdb/connections.py|defaulterrorhandler|35])
Run Code Online (Sandbox Code Playgroud)
另一个错误供参考
error: uncaptured python exception, closing channel
<twitstream.twitasync.TwitterStreamPOST connected at
0x7feb9d52b7e8> (<class '_mysql_exceptions.ProgrammingError'>:
(1064, "You have an error in …Run Code Online (Sandbox Code Playgroud) 我正在实现一个Python本体类,它使用数据库后端来存储和查询本体.数据库模式是固定的(事先指定),但我不知道正在使用什么类型的数据库引擎.但是,我可以依赖数据库引擎的Python接口使用Python DB-API 2.0(PEP 249)的事实.一个直截了当的想法是让用户将符合PEP 249的Connection对象传递给我的本体的构造函数,然后使用各种硬编码的SQL查询来查询数据库:
class Ontology(object):
def __init__(self, connection):
self.connection = connection
def get_term(self, term_id):
cursor = self.connection.cursor()
query = "SELECT * FROM term WHERE id = %s"
cursor.execute(query, (term_id, ))
[...]
Run Code Online (Sandbox Code Playgroud)
我的问题是允许不同的数据库后端支持查询中的不同参数标记,由paramstyle后端模块的属性定义.例如,如果paramstyle = 'qmark',接口支持问号样式(SELECT * FROM term WHERE id = ?); paramstyle = 'numeric'表示数字,位置样式(SELECT * FROM term WHERE id = :1); paramstyle = 'format'表示ANSI C格式的字符串样式(SELECT * FROM term WHERE id = %s).如果我想让我的类能够处理不同的数据库后端,似乎我必须为所有参数标记样式做准备.这似乎打败了我的通用DB …
我正在创建一个需要访问数据库的RESTful API.我正在使用Restish,Oracle和SQLAlchemy.但是,我会尝试尽可能一致地构建我的问题,而不考虑Restish或其他Web API.
我希望能够为执行查询的连接设置超时.这是为了确保放弃长时间运行的查询,并丢弃(或回收)连接.此查询超时可以是全局值,这意味着,我不需要根据查询或连接创建更改它.
给出以下代码:
import cx_Oracle
import sqlalchemy.pool as pool
conn_pool = pool.manage(cx_Oracle)
conn = conn_pool.connect("username/p4ss@dbname")
conn.ping()
try:
cursor = conn.cursor()
cursor.execute("SELECT * FROM really_slow_query")
print cursor.fetchone()
finally:
cursor.close()
Run Code Online (Sandbox Code Playgroud)
如何修改上面的代码来设置查询超时?此超时是否也适用于连接创建?
这类似于java.sql.Statement的setQueryTimeout(int seconds)方法在Java中的作用.
谢谢
我研究过的文档表明,为其他数据库执行此操作的方法是在查询中使用多个语句,a:
>>> cursor = connection.cursor()
>>> cursor.execute("set session transaction isolation level read uncommitted;
select stuff from table;
set session transaction isolation level repeatable read;")
Run Code Online (Sandbox Code Playgroud)
不幸的是,这样做没有结果,因为显然Python DB API(或者只是它的实现?)不支持单个查询中的多个记录集.
过去有没有其他人成功?
python-db-api ×10
python ×9
mysql ×3
sql ×2
cx-oracle ×1
database ×1
json ×1
oracle ×1
postgresql ×1
psycopg2 ×1
python-2.7 ×1
resultset ×1
sql-like ×1
sqlite ×1