I want to be able to get all the information from MySQLdb using the SELECT * FROM query. I have the following code:
database = MySQLdb.connect("127.0.0.1", "root", "pswd", "Kazzah")
cursor = database.cursor()
cursor.execute("SELECT * FROM Accounts WHERE Email=%s AND Password=%s", (_Email, _Password))
database.commit()
numrows = cursor.rowcount
results = cursor.fetchall()
print numrows
for result in results:
print result
How can I make variables that hold each piece of info from result. If it result returns:
(28L, 'Name', 'Last', 'email#email.com', 'pswd', '10000')
I want to make a variable called ID and get the first part of the result which is 28L, and so forth with each other pieces of information.
Thank you!
Edit
To set the full set of data use this :
id, fname, lname, email, pswd, whatever = result
And for particular values, try indexing.
Related
I write to see how I can get only one data to show by a print when I make a query in python, when I do the query it should only give me a number but I cannot show or access it.
def run_query(self, query, parameters = ()):
with sqlite3.connect(self.db_name) as conn:
cursor = conn.cursor()
result = cursor.execute(query, parameters)
conn.commit()
return result
def get_horarios(self):
query = 'SELECT hora FROM horarios where horario=1'
db_rows = self.run_query(query)
print(db_rows)
To show the first row in the results of the query:
print(db_rows.fetchone())
To show all of the results of the query:
print(db_rows.fetchall())
or
for row in db_rows.fetchall():
print(row)
The query always return a list. To access the first item, you can do:
print(db_rows[0])
I'm trying to write a python script to get a count of some tables for monitoring which looks a bit like the code below. I'm trying to get an output such as below and have tried using python multi-dimensional arrays but not having any luck.
Expected Output:
('oltptransactions:', [(12L,)])
('oltpcases:', [(24L,)])
Script:
import psycopg2
# Connection with the DataBase
conn = psycopg2.connect(user = "appuser", database = "onedb", host = "192.168.1.1", port = "5432")
cursor = conn.cursor()
sql = """SELECT COUNT(id) FROM appuser.oltptransactions"""
sql2 = """SELECT count(id) FROM appuser.oltpcases"""
sqls = [sql,sql2]
for i in sqls:
cursor.execute(i)
result = cursor.fetchall()
print('Counts:',result)
conn.close()
Current output:
[root#pgenc python_scripts]# python multi_getrcount.py
('Counts:', [(12L,)])
('Counts:', [(24L,)])
Any help is appreciated.
Thanks!
I am a bit reluctant to show this way, because best practices recommend to never build a dynamic SQL string but always use a constant string and parameters, but this is one use case where computing the string is legit:
a table name cannot be a parameter in SQL
the input only comes from the program itself and is fully mastered
Possible code:
sql = """SELECT count(*) from appuser.{}"""
tables = ['oltptransactions', 'oltpcases']
for t in tables:
cursor.execute(sql.format(t))
result = cursor.fetchall()
print("('", t, "':,", result, ")")
I believe something as below, Unable to test code because of certificate issue.
sql = """SELECT 'oltptransactions', COUNT(id) FROM appuser.oltptransactions"""
sql2 = """SELECT 'oltpcases', COUNT(id) FROM appuser.oltpcases"""
sqls = [sql,sql2]
for i in sqls:
cursor.execute(i)
for name, count in cursor:
print ("")
Or
sql = """SELECT 'oltptransactions :'||COUNT(id) FROM appuser.oltptransactions"""
sql2 = """SELECT 'oltpcases :'||COUNT(id) FROM appuser.oltpcases"""
sqls = [sql,sql2]
for i in sqls:
cursor.execute(i)
result = cursor.fetchall()
print(result)
For my school project I decided to make a physics revision tool. The tool lets users log in and saves information about their performance on certain questions. As a result of this I realised I needed to name each table used to store each individual users scores so I thought using .format would be appropriate. It seemed to be working fine until the point where i needed to add code that would add information to the table. From the testing i have done on the code so far, i think the problem is because i am using .format it won't actually create any columns. I don't know how to get around that please help. Appropriate sections of code have been provided:
def quesprep():
intro.destroy()
con= sqlite3.connect("login.db")
c= con.cursor()
c.execute("SELECT accid FROM credentials WHERE accountname = ?", (user,))
global results
results=c.fetchall()
con.commit()
con.close()
con= sqlite3.connect("store.db")
c= con.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS {}(mod integer, ques integer,score integer)""".format(results))
c.execute("INSERT INTO {} Values(mod=2,ques=1, score=0)".format(results))
con.commit()
con.close()
ques()
def mod2q1page():
questionspage.destroy()
con= sqlite3.connect("login.db")
c= con.cursor()
c.execute("SELECT accid FROM credentials WHERE accountname = ?", (user,))
global results
results=c.fetchall()
con.commit()
con= sqlite3.connect("store.db")
c= con.cursor()
c.execute("INSERT OR IGNORE INTO {} VALUES(mod=2, ques=2, score=0)" .format(results))
There seems to be several things wrong here.
Format takes a variable inside the {} ... like {0}, {1} etc
Placeholders are the preferred route to take with formatting sql queries ... like you did in your SELECT
I am not sure what the issue is here but if you are trying to add columns, you need to ALTER the table ... not INSERT. INSERT will add a row item. If you can post the error, perhaps we can help a little more. To start you out though, try placeholders in lieu of format.
Also, fetchall returns a list of tuples ... need to send a tuple in sql, not a list.
for x in results:
c.execute("INSERT INTO ? (col1, col2, col3) VALUES (1, 2, 3);", x)
Edit:
I stand corrected - I ran this code:
data = [('user',)]
cursor.execute("INSERT INTO ? (id, email, password) VALUES (1, test, test);", data)
syntax error because you cannot add placeholder to table name. Read here
I used format with the {0}:
cursor.execute("INSERT INTO {0} (id, email, password) VALUES (1, test, test);".format('user'))
The query was successful. I believe that is your problem here.
found a solution:
intro.destroy()
con= sqlite3.connect("login.db")
c= con.cursor()
c.execute("SELECT accountname FROM credentials WHERE accountname = ?", (user,))
results=c.fetchone()
global tablename
tablename=" ".join(map(str, (results)))
con.commit()
con.close()
global m
m="mod"
global q
q="ques"
global s
s="score"
fieldtype="INTEGER"
con=sqlite3.connect("store.db")
c=con.cursor()
c.execute('CREATE TABLE IF NOT EXISTS {} ({fc} {ft}, {sc} {ft2}, {tc} {ft3})'\
.format(tablename, fc=m, ft=fieldtype, sc=q, ft2=fieldtype, tc=s,
ft3=fieldtype))
con.commit()
con.close()
I have a SQL database file which contains a multitude of columns, two of which are 'GEO_ID' and 'MED_INCOME'. I am trying to retrieve just the 'MED_INCOME' column data using the associated 'GEO_ID'. Here is what I thought would work:
import sqlite3 as db
def getIncome(censusID):
conn = db.connect('census.db')
c = conn.cursor()
c.execute("SELECT 'MED_INCOME' FROM censusDbTable WHERE GEO_ID = %s" % (censusID)
response = c.fetchall()
c.close()
conn.close()
return response
id = 60014001001
incomeValue = getIncome(id)
print("incomeValue: ", incomeValue)
Which results in:
incomeValue: [('MED_INCOME',)]
I thought that I had used this method before when attempting to retrieve the data from just one column, but this method does not appear to work. If I were to instead write:
c.execute("SELECT * FROM censusDbTable WHERE GEO_ID = %s" % (censusID)
I get the full row's data, so I know the ID is in the database file.
Is there something about my syntax that is causing this request to result in an empty set?
Per #Ernxst comment, I adjusted the request to:
c.execute("SELECT MED_INCOME FROM censusDbTable WHERE GEO_ID = %s" % (censusID)
Removing the quotes around the column ID, which solved the problem.
I am trying to print SQL result through python code, where I an trying to pass different predicates of the where clause from a for loop. But the code only taking the last value from the loop and giving the result.
In the below example I have two distinct id values 'aaa' and 'bbb'. There are 4 records for id value = 'aaa' and 2 records for the id value = 'bbb'.
But the below code only giving me the result for the id value ='bbb' not for id value 'aaa'
Can anyone help to identify what exactly wrong I am doing?
import pymysql
db = pymysql.connect(host="localhost", user="user1", passwd="pass1", db="db1")
cur = db.cursor()
in_lst=['aaa', 'bbb']
for i in in_lst:
Sql = "SELECT id, val, typ FROM test123 Where id='{inpt}'".format(inpt=i)
print(Sql)
cur.execute(Sql)
records = cur.fetchall()
print(records)
db.close()
The result I am getting as below
C:\Python34\python.exe C:/Users/Koushik/PycharmProjects/Test20161204/20170405.py
SELECT id, val, typ FROM test123 Where id='bbb'
(('bbb', 5, '1a'), ('bbb', 17, '1d'))
Process finished with exit code 0
import pymysql
db = pymysql.connect(host="localhost", user="root", passwd="1234", db="sakila")
cur = db.cursor()
in_lst=['1', '2']
for i in in_lst:
Sql = "SELECT * FROM actor Where actor_id='{inpt}'".format(inpt=i)
print(Sql)
cur.execute(Sql)
records = cur.fetchall()
print(records)
db.close()
Indentation is your problem, please update the code according to your needs...
Within your for loop, you're formatting the sql statement to replace "{inpt}" with "aaa". However, before you do anything with that value, you're immediately overwriting it with the "bbb" version.
You would need to either:
Store the results somehow before the next iteration of the loop, then process them outside of the loop.
Process the results within the loop.
Something like the following will give you a list containing both results from the fetchall() calls:
import pymysql
db = pymysql.connect(host="localhost", user="user1", passwd="pass1", db="db1")
cur = db.cursor()
in_lst=['aaa', 'bbb']
records = list()
for i in in_lst:
Sql = "SELECT id, val, typ FROM test123 Where id='{inpt}'".format(inpt=i)
print(Sql)
cur.execute(Sql)
records.append(cur.fetchall())
print(records)
db.close()