Python: Print only one value of an SQL query result set - python

from sqlalchemy import create_engine
engine = create_engine('mssql+pymssql://myusername:mypassword#127.0.0.1:1433/AQOA_Core')
connection = engine.connect()
result = connection.execute("""SELECT DISTINCT Distributor FROM Product""")
for row in result:
print row[0]
connection.close()
The above code returns a result set as:
FRANCETV
GAUMONT
M6SND
PATHE
STUDIOCANAL
TF1
WARNER
What if I want to print just one value without changing the query?
Tried print row[0][1], print row[0:1] This was tried to print just the first value FRANCETV
Basically I want to be able to print each one of the values in the result set seperately without making changes to the query.

You can try to access the data by:
connection = engine.connect()
result = connection.execute("""SELECT DISTINCT Distributor FROM Product""")
result_list = result.fetchall()
result_list[0][0]
connection.close()

If you take a look at the pymssql docs, you'll see the cursor object has a fetchone() method.
with engine.connect() as connection:
cursor = connection.cursor()
cursor.execute("""SELECT DISTINCT Distributor FROM Product""")
first_row = cursor.fetchone()
print first_row

file = open("testfile.txt", "w", encoding='utf-8')
mycursor.execute('SELECT * from COMPANY')
myresult = mycursor.fetchall()
counter = 0
y = 0
for x in myresult:
y = 0
while y < 3:
print(y)
file.write("%s\n" % myresult[counter][y])
y = y + 1
counter = counter + 1
file.close()
This is what I concluded from the answers above

Related

Why wont this loop?

Newby working my way through python and sql with mariadb.
Why wont this loop? It updates the first record only. Im pretty hack at this...
cursor1.execute("select recordid, mvavgvol, quote_usd_volume_change_24h from pumped")
records = cursor1.fetchall()
for x in records:
rid = (x[0])
m = (x[1])
o = (x[2])
if (m >= o):
result = 0
else:
result = 1
upd_data=(result,rid)
sql1 = ("UPDATE pumped SET mvavgvolcheck = %s WHERE recordid = %s")
cursor2.execute(sql1,upd_data)
conn.commit()
Since you are fetching multiple rows you have to store the fetched values in an array and use cursor's executemany() method instead.
✂
data= []
for x in records:
rid = (x[0])
result= int(x[1] > x[2])
data+= [(result, rid)]
cursor.executemany(UPDATE pumped SET mvavgvolcheck = %s WHERE recordid = %s", data);
✂
When using mariadb python module (MariaDB Connector/Python) this is much more effective since it reduces network traffic: instead of sending n update commands in a loop (where n is the number of rows in table pumped) only one command will be send to the server.
conn = msql.connect(host=Host,port=Port, user=User, password=Password, database=database)
cursor1 = conn.cursor()
cursor2 = conn.cursor()
cursor1.execute("select recordid, mvavgvol, quote_usd_volume_change_24h from pumped")
records = cursor1.fetchall()
for x in records:
rid = (x[0])
m = (x[1])
o = (x[2])
if (m >= o):
result = 0
cursor2.execute("UPDATE pumped SET mvavgvolcheck = %s WHERE recordid = %s",(result, rid))
conn.commit()
else:
result = 1
cursor2.execute("UPDATE pumped SET mvavgvolcheck = %s WHERE recordid = %s",(result, rid))
conn.commit()

How to load column names from Amazon Redshift with Psycopg? [duplicate]

So currently when I execute SELECT query and retrieve data I have to get results like this:
connection = psycopg2.connect(user="admin",
password="admin",
host="127.0.0.1",
port="5432",
database="postgres_db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM user")
users = cursor.fetchall()
for row in users:
print(row[0])
print(row[1])
print(row[2])
What I want to do is, use column names instead of integers, like this:
for row in users:
print(row["id"])
print(row["first_name"])
print(row["last_name"])
Is this possible, and if it is, then how to do it?
You need to use RealDictCursor, then you can access the results like a dictionary:
import psycopg2
from psycopg2.extras import RealDictCursor
connection = psycopg2.connect(user="...",
password="...",
host="...",
port="...",
database="...",
cursor_factory=RealDictCursor)
cursor = connection.cursor()
cursor.execute("SELECT * FROM user")
users = cursor.fetchall()
print(users)
print(users[0]['user'])
Output:
[RealDictRow([('user', 'dbAdmin')])]
dbAdmin
no need to call fetchall() method, the psycopg2 cursor is an iterable object you can directly do:
cursor.execute("SELECT * FROM user")
for buff in cursor:
row = {}
c = 0
for col in cursor.description:
row.update({str(col[0]): buff[c]})
c += 1
print(row["id"])
print(row["first_name"])
print(row["last_name"])

Check if a certain number exists in a database using python and add 1 to a variable

I am trying to check if a certain number exists in a database using python.
When it detects the number I am looking for, then I want it to do variable += 1. I do not have any specific code, but here is some example code of what I want it to do.
import pyodbc
one = 0
conn = pyodbc.connect(r'DSN=MACCD')
cursor = conn.cursor()
cursor.execute('SELECT first,second,third,fourth,fifth FROM ExampDatabase')
if "1 is detected in the database":
one += 1
print(one)
Reading the pyodbc docs, you could try this:
import pyodbc
conn = pyodbc.connect(...)
cursor = conn.cursor()
cursor.execute(...)
# whatever number you are looking for
my_target = ...
target_counter = 0
row_counter = 0
while True:
row = cursor.fetchone()
if row is None:
break
row_counter += 1
print(row_counter, row)
if my_target in row:
target_counter += 1
print('rows returned:', row_counter)
print('targets found:', target_counter)

Query Oracle Database by Python

I want query Database by using python
This is my code:
import cx_Oracle
import os
def GetDatabase(queryCommand, row):
conn = cx_Oracle.connect('Bell/Bell##nn.nnn.nnn.nn:1521/Bell')
cur = conn.cursor()
cur.execute(queryCommand)
res=cur.fetchone()
i = 0
while (i < row):
if cur.rowcount == row:
print res
res=cur.fetchone()
i = i + 1
cur.close()
conn.close()
tup1=GetDatabase("select Name from ContactPoint where EmployeeID='1234'",2)
This is output
('KANOK BKK',)
I just want value (I don't want parentheses and a comma)
I try print tup1[0] but it is not working.
you should use yield instead of print, or put res into a list and return it, as print just write it to sys.stdout.
for row in tup1:
print(row[0])

Python cursor is returning number of rows instead of rows

Writing a script to clean up some data. Super unoptimized but this cursor is
returning the number of results in the like query rather than the rows what am I doing wrong.
#!/usr/bin/python
import re
import MySQLdb
import collections
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="admin", # your username
passwd="", # your password
db="test") # name of the data base
# you must create a Cursor object. It will let
# you execute all the query you need
cur = db.cursor()
# Use all the SQL you like
cur.execute("SELECT * FROM vendor")
seen = []
# print all the first cell of all the rows
for row in cur.fetchall() :
for word in row[1].split(' '):
seen.append(word)
_digits = re.compile('\d')
def contains_digits(d):
return bool(_digits.search(d))
count_word = collections.Counter(seen)
found_multi = [i for i in count_word if count_word[i] > 1 and not contains_digits(i) and len(i) > 1]
unique_multiples = list(found_multi)
groups = dict()
for word in unique_multiples:
like_str = '%' + word + '%'
res = cur.execute("""SELECT * FROM vendor where name like %s""", like_str)
You are storing the result of cur.execute(), which is the number of rows. You are never actually fetching any of the results.
Use .fetchall() to get all result rows or iterate over the cursor after executing:
for word in unique_multiples:
like_str = '%' + word + '%'
cur.execute("""SELECT * FROM vendor where name like %s""", like_str)
for row in cur:
print row

Categories

Resources