Multiqueries with python/mysql - python

I'm using MysqlDB. Does it provide a way to execute multiple SELECT queries like mysqli_multi_query does? If not, is there a python library that would allow that?
There is executemany, but that's not what I'm looking for. I'm working with Sphinx and trying to get its batch queries to work.

I spent some time to dig in the source code of MySQLdb and the answer is YES you can do multiple queries with it:
import MySQLdb
db = MySQLdb.connect(user="username", db="dbname")
cursor = db.cursor()
batch_queries = '''
SELECT * FROM posts WHERE id=1;
SELECT * FROM posts WHERE id=2;
'''
cursor.execute(batch_queries)
print cursor.fetchone()
while cursor.nextset(): # iterate to next result set if there is any
print cursor.fetchone()
cursor.close()
Tested successfully in my localhost. Hope it helps.

Related

psycopg2 returns single row in output

import psycopg2
from contextlib import closing
import inspect
db = psycopg2.connect(<credentials>)
query = "SELCT * FROM \
<tablename> \
LIMIT 100;"
with closing(db.cursor()) as cur:
cur.execute(query)
results = cur.fetchall()
print(len(results))
db.close()
With the above simple query and code, I am trying to read results from a SELECT query but the results object always have a single record instead of all. Query is working fine in pgadmin query tool, how do I fix this? Thanks in advance for any suggestions here.
Edit #1 (for snakecharmerb): While checking / printing results, I am always getting a single row correctly giving the query results.
Edit #2 (for Expurple): Thanks for the suggestion, will try that. I believe that is not affecting the overall query result.

About python sqlite3 order by

Now, I have a study about python sqlite3 database. I think it is very simple problem but not allow next step. Could help me?
There is print OK on vscode terminal, but not revised to DB file. I'm searching several times but I can not fix it.
If I execute the code, it not sorting on DB files.
import sqlite3
conn = sqlite3.connect('sqliteDB1.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM member")
temp123 = cursor. fetchall()
print(temp123)
cursor.execute("SELECT * FROM member ORDER BY -code")
temp321 = cursor.fetchall()
conn.commit
print(temp321)
conn.close()
A select statement just returns data from a database, it will not modify it. Moreover, tables in SQL databases are inherently unordered sets. They have no intrinsic value, and you should never rely on the order of the rows that happens to be returned unless you explicitly sort it with an order by clause.

SELECT in a while loop in python with mysql

I am trying to find the latest entry in a MySQL database by using a query with SELECT MAX(id). I already get the latest id, so I know the query works, but now I want to use it in a while loop so I keep getting the latest entry with each iteration.
This is what I have so far:
import pymysql
con = pymysql.connect(host='.....', user='.....',
password='.....', database='.....')
cur = con.cursor()
while True:
query = "SELECT MAX(id) FROM reports"
cur.execute(query)
data = cur.fetchall()
last = (data[0][0])
print(last)
The problem is that I keep getting the same result after updating the database. For instance, right now I have 45 entries, so my script prints '45' in a while loop. But after I add another row to the table it keeps printing '45' instead of the '46' I would expect. When I stop the script and run it again, it will print '46' and keep printing this even after I add another row.
I have only started working with MySQL about two weeks ago, so I don't have all that much knowledge about it. I feel like I'm missing something really small here. What should I do? Any help would be greatly appreciated.
I had this same problem, and just wanted to make it clear for anyone else searching for the solution.
Setting autocommit to True solved my issue and didn't require calling a commit after each query.
import pymysql
con = pymysql.connect(host='.....', user='.....',
password='.....', database='.....')
con.autocommit = True
cur = con.cursor()
while True:
query = "SELECT MAX(id) FROM reports"
cur.execute(query)
data = cur.fetchall()
last = (data[0][0])
print(last)
Here is a link to the documentation

Python 3.4.3 and PySqlite3 not Inserting content on Table

Actually I'm working on a Python and SQLite based url Shortener that will allow people to shorten their urls. But I'm in a trouble, so thats why I'm here hehe! So, my code is not inserting a thing into the database!
This is the connection and insertion code:
connection = sqlite3.connect(DBSource)
cursor = connection.cursor()
query = "INSERT INTO URLStorage VALUES('{0}','{1}','{2}')".format(urlFinal, urlprocessar, datetime.datetime.now())
#return(query)
cursor.execute(query)
If you want to take a look at the full source code to see if I mess something else, this is the link for it: https://github.com/vmesel/WP-A.CO
you want either a commit or close after you execute the query:
connection.commit()
or
connection.close()

How to get database name from postgres/mysql cursor object

I have a several postgres and mysql cursor objects exposed to me, created in some universe. How to find the database name (and other info about that db) from these cursor objects?
cursor.__dict__ gives nothing useful.
If you also have the connection (call it conn):
conn.info.dbname
I don't know about postgres but using MySQLdb you could always use the following:
cursor.execute("select database()")
db_name = cursor.fetchone()[0]
Maybe there's a cleaner way to do this...
Edit:
for other info it depends on what exactly you're looking for but for example to fetch table names
cursor.execute("show tables")
for r in cursor.fetchall():
print r[0]
There are many other functions available... Is there anything specific you're looking for?
for postgresql:-
cursor.execute("select current_database()")
db_name = cursor.fetchone()[0]

Categories