How to get a single result from a SQL query in python?
I think you’re looking for Cursor.fetchone() : cursor.fetchone()[0]
I think you’re looking for Cursor.fetchone() : cursor.fetchone()[0]
The cursor paradigm is not specific to Python but are a frequent data structure in databases themselves. Depending on the underlying implementation it may be possible to generate several cursors sharing the same connection to a database. Closing the cursor should free resources associated to the query, including any results never fetched from the DB … Read more
For anyone who’d like to work with the sqlite3 lib regardless of its shortcomings, I found that you can keep some control of transactions if you do these two things: set Connection.isolation_level = None (as per the docs, this means autocommit mode) avoid using executescript at all, because according to the docs it “issues a … Read more
Yeah, this is a real mess. Both MySQL and PostgreSQL use backslash-escapes for this by default. This is a terrible pain if you’re also escaping the string again with backslashes instead of using parameterisation, and it’s also incorrect according to ANSI SQL:1992, which says there are by default no extra escape characters on top of … Read more
cursor.rowcount will usually be set to 0. If, however, you are running a statement that would never return a result set (such as INSERT without RETURNING, or SELECT … INTO), then you do not need to call .fetchall(); there won’t be a result set for such statements. Calling .execute() is enough to run the statement. … Read more
As per official psycopg2 documentation fetchone() Fetch the next row of a query result set, returning a single tuple, or None when no more data is available: >>> cur.execute(“SELECT * FROM test WHERE id = %s”, (3,)) >>> cur.fetchone() (3, 42, ‘bar’) A ProgrammingError is raised if the previous call to execute*() did not produce … Read more