Error while fetching data from PostgreSQL column "user2" does not exist - python-3.x

My Django views.py passes a email address to a python function. The
python function queries a PostgreSQL table using a where clause. The
where clause is equal to the email address that was passed in
(someuser). My goal is to retrieve the userid value for this email
address. But I get an error message telling me that there is no column
called "user2" which is correct (there is not). But why does the
select see that as an existing column?
I print the email out only to verify that it got passed in. someuser
for select= user2#gmail.com
Error while fetching data from PostgreSQL
column "user2" does not exist LINE 1: SELECT userid from accounts_user
WHERE email = user2#gmail.c...
I have ran this locally on my Windows 10 box as well as on AWS Cloud9
with the same result. It tells me that no column exists that begins
with the email address up to the '#' sign.
import psycopg2
def get_userid(someuser):
try:
connection = psycopg2.connect(bla, bla")
cursor = connection.cursor()
print("someuser for select= ", someuser)
postgreSQL_select_Query = ("""SELECT userid from accounts WHERE email = %s;""" %(someuser))
cursor.execute(postgreSQL_select_Query)
mobile_records = cursor.fetchall()
for row in mobile_records:
print("userid = ", row[0], )
except (Exception, psycopg2.Error) as error :
print ("Error while fetching data from PostgreSQL", error)
finally:
if(connection):
cursor.close()
if __name__ == '__main__':
get_userid()
table has this:
id | email | userid
----+------------------------+--------
18 | user2#gmail.com | u48923
I expect to get the userid of "u48923" after running the select.

Change it to the following
postgreSQL_select_Query = ("""SELECT userid from accounts WHERE email = '%s';""" %(someuser))
But a better way is to use the built in functionality of psycopg2 and write it as follows
cursor.execute("""SELECT userid from accounts WHERE email = %s;""", (someuser,))
Psycopg2 Documentation

def getEmail(someuser): print("received someuser in 'run_select' from views.py= ", someuser) try:
connection = psycopg2.connect(user="my user",
password="xxxxxx",
host="127.0.0.1",
port="5432",
database="my_db")
cursor = connection.cursor()
print("again someuser for select= ", someuser)
someuser = str(someuser) # convert to string or you get: Error while fetching data from PostgreSQL can't adapt type 'User'
print("someuser= ", someuser)
cursor.execute("""SELECT userid from accounts_user WHERE email = %s""", (someuser,))
print("Selecting rows from c9_max_forms_kw using cursor.fetchall")
mobile_records = cursor.fetchall()
print("Print each row and it's columns values")
for row in mobile_records:
print("Id = ", row[0], )
#print("email = ", row[5])
#print("userid = ", row[9], "\n") # should be "u48923"
#save = ''.join(row[9]) # convert this tuple to a string except (Exception, psycopg2.Error) as error :
print ("Error while fetching data from PostgreSQL", error) finally:
#closing database connection.
if(connection):
cursor.close()
connection.close()
print("PostgreSQL connection is closed") return someuser
Joshua is the man. The string conversion was the key. The error given without it doesn't seem to make sense to me. Best to all. Ken.

Related

Python - Deleting Treeview record from table & SQLite

I'm currently trying to make a 'delete record' button that deletes a treeview record, this part works within the treeview table, however I am unable to get the record in the SQLite database to be deleted aswell.
def deleterec():
try:
curItem = tree1.focus()
valueList=tree1.item(curItem,'values')
global selectedItem2
selectedItem2=valueList[0]
prodID = tree1.selection()[0] # get selected item from tree
messageDelete = messagebox.askyesno("Confirmation", "Do you want to permanently delete this record?")
if messageDelete > 0:
# Remove one record
tree1.delete(prodID)
print(selectedItem2) #this prints the accurate productID that's in my SQLite database
global conn87
conn87 = sqlite3.connect('Sqlite_Python.db')
#Create cursor instant
global c87
c87 = conn87.cursor()
print("Successfully Connected to SQLite")
sqlite_delete_queryL = str(f"""DELETE from stockDatabase WHERE productID='%s';""") % selectedItem2
c87.execute(str(sqlite_delete_queryL))
c87.close()
except sqlite3.Error as error:
print("Error: ", error)
finally:
if conn87:
conn87.close()
print("sqlite connection is closed")
My code is not outputting any errors and it is giving the confirmation that the connection is successfully made then closed, however the query is not complete.............

relation does not exist in postgreSQL but already exist

I've read a lot of articles about my problem but no one solve it. So u can see my code here
DATABASE_URL = os.environ.get('url_of_my_db')
con = None
try:
con = psycopg2.connect(DATABASE_URL)
cur = con.cursor()
print('PostgreSQL database version:')
#cur.execute('SELECT version()')
#cur.execute('SELECT * FROM qwerty')
#cur.execute(sql.SQL('SELECT * FROM {}').format(sql.Identifier('qwerty')))
#cur.execute(sql.SQL("INSERT INTO {} (chat_id, username, created_on) VALUES (8985972942, vovakirdan, 2022-01-05)").format(sql.Identifier('users')))
cur.execute("""INSERT INTO users (chat_id, username, created_on)
VALUES (3131,
vovakirdan,
2022-01-05)""")
# display the PostgreSQL database server version
db_version = cur.fetchone()
print(db_version)
# close the communication with the HerokuPostgres
cur.close()
except Exception as error:
print('Cause: {}'.format(error))
finally:
# close the communication with the database server by calling the close()
if con is not None:
con.close()
print('Database connection closed.')
and in my DB table named "users" (named without quotes) are exist, but I still have this error:
error
...relation "users" does not exist
all the #commented code doesn't work and send the same error besides SELECT version(), it works perfectly that proves that connection works.
The problem was that PostgreDB wants me to use SELECT colum FROM schema.table instead of SELECT colum FROM table. And that's all. Thanks everyone

How can I return a string from a Google BigQuery row iterator object?

My task is to write a Python script that can take results from BigQuery and email them out. I've written a code that can successfully send an email, but I am having trouble including the results of the BigQuery script in the actual email. The query results are correct, but the actual object I am returning from the query (results) always returns as a Nonetype.
For example, the email should look like this:
Hello,
You have the following issues that have been "open" for more than 7 days:
-List issues here from bigquery code
Thanks.
The code reads in contacts from a contacts.txt file, and it reads in the email message template from a message.txt file. I tried to make the bigquery object into a string, but it still results in an error.
from google.cloud import bigquery
import warnings
warnings.filterwarnings("ignore", "Your application has authenticated using end user credentials")
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from string import Template
def query_emailtest():
client = bigquery.Client(project=("analytics-merch-svcs-thd"))
query_job = client.query("""
select dept, project_name, reset, tier, project_status, IssueStatus, division, store_number, top_category,
DATE_DIFF(CURRENT_DATE(), in_review, DAY) as days_in_review
from `analytics-merch-svcs-thd.MPC.RESET_DETAILS`
where in_review IS NOT NULL
AND IssueStatus = "In Review"
AND DATE_DIFF(CURRENT_DATE(), in_review, DAY) > 7
AND ready_for_execution IS NULL
AND project_status = "Active"
AND program_name <> "Capital"
AND program_name <> "SSI - Capital"
LIMIT 50
""")
results = query_job.result() # Waits for job to complete.
return results #THIS IS A NONETYPE
def get_queryresults(results): #created new method to put query results into a for loop and store it in a variable
for i,row in enumerate(results,1):
bq_data = (i , '. ' + str(row.dept) + " " + row.project_name + ", Reset #: " + str(row.reset) + ", Store #: " + str(row.store_number) + ", " + row.IssueStatus + " for " + str(row.days_in_review)+ " days")
print (bq_data)
def get_contacts(filename):
names = []
emails = []
with open(filename, mode='r', encoding='utf-8') as contacts_file:
for a_contact in contacts_file:
names.append(a_contact.split()[0])
emails.append(a_contact.split()[1])
return names, emails
def read_template(filename):
with open(filename, 'r', encoding='utf-8') as template_file:
template_file_content = template_file.read()
return Template(template_file_content)
names, emails = get_contacts('mycontacts.txt') # read contacts
message_template = read_template('message.txt')
results = query_emailtest()
bq_results = get_queryresults(query_emailtest())
import smtplib
# set up the SMTP server
s = smtplib.SMTP(host='smtp-mail.outlook.com', port=587)
s.starttls()
s.login('email', 'password')
# For each contact, send the email:
for name, email in zip(names, emails):
msg = MIMEMultipart() # create a message
# bq_data = get_queryresults(query_emailtest())
# add in the actual person name to the message template
message = message_template.substitute(PERSON_NAME=name.title())
message = message_template.substitute(QUERY_RESULTS=bq_results) #SUBSTITUTE QUERY RESULTS IN MESSAGE TEMPLATE. This is where I am having trouble because the Row Iterator object results in Nonetype.
# setup the parameters of the message
msg['From']='email'
msg['To']='email'
msg['Subject']="This is TEST"
# body = str(get_queryresults(query_emailtest())) #get query results from method to put into message body
# add in the message body
# body = MIMEText(body)
#msg.attach(body)
msg.attach(MIMEText(message, 'plain'))
# query_emailtest()
# get_queryresults(query_emailtest())
# send the message via the server set up earlier.
s.send_message(msg)
del msg
Message template:
Dear ${PERSON_NAME},
Hope you are doing well. Please find the following alert for Issues that have been "In Review" for greater than 7 days.
${QUERY_RESULTS}
If you would like more information, please visit this link that contains a complete dashboard view of the alert.
ISE Services
The BQ result() function returns a generator, so I think you need to change your return to yield from.
I'm far from a python expert, but the following pared-down code worked for me.
from google.cloud import bigquery
import warnings
warnings.filterwarnings("ignore", "Your application has authenticated using end user credentials")
def query_emailtest():
client = bigquery.Client(project=("my_project"))
query_job = client.query("""
select field1, field2 from `my_dataset.my_table` limit 5
""")
results = query_job.result()
yield from results # NOTE THE CHANGE HERE
results = query_emailtest()
for row in results:
print(row.field1, row.field2)

data is not inserted into oracle database from python

Hi i'm a newbie to coding.i have written a code for registration form and the code run without an error.
def clicked():
try:
con = cx_Oracle.connect('app/reshmaa#10.23.129.216/XE')
cur = con.cursor()
emp_id=txt.get()
first_name=txt1.get()
last_name=txt2.get()
email_id=txt3.get()
"""if re.match("^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$",email_id,re.IGNORECASE):
email_id=txt3.get()"""
mobile_no=int(txt4.get())
last_update=str(date.today())
statement="insert into registration(emp_id, first_name, last_name, email_id, mobile_no, last_update, pass_word) values('%s', '%s', '%s', '%s','%s',to_date('%s','dd/mm/yyyy'),'%s')"%
(emp_id, first_name,last_name,email_id,mobile_no, last_update, pass_word)
cur.execute(statement)
con.commit()
max_char= 8
allchar= string.ascii_letters + string.digits + '!##$%&*'
random.seed=(os.urandom(16))
pass_word= "".join(random.choice(allchar) for x in range(max_char))
messagebox.showinfo("Success","Your password is "+ pass_word)
except:
messagebox.showerror("Error","Check Your Details")
btn = Button(window, text="Register", bg="dodgerblue4", fg="silver", command=clicked)
btn.grid(column=5, row=7)
When i click register button it shows the error message box in except statement and stops. It does not show any error in the python shell(version 3.6.2) and the data entered is not inserted into my oracle database table.
can someone help me with what error has been made in my code?

rest server centos 7 and python 3 doesnt seem work well

I have a rest server that i use it in the my main program ; rest server is running on centos 7 vps when i run the main on my laptop which is windows 7 it works as well; but when i run the main as a service on the same vps server it doesn't work well i've checked every single possible problems even changing unicode but i wouldn't find a solution yet.
here is my rest server code:
from bottle import route, run, redirect
import sqlite3
db = sqlite3.connect("checkLink.db")
db.execute("DROP TABLE IF EXISTS checkLink")
db.execute("CREATE TABLE checkLink(user_id INT, link TEXT, join_link TEXT,
check_id INT)")
db.execute("CREATE UNIQUE INDEX user_id ON checkLink(user_id, link,
join_link, check_id)")
db.commit()
def database(user_id, link):
db2 = sqlite3.connect("checkLink.db")
db2.row_factory = sqlite3.Row
cursor = db2.execute("SELECT * FROM checkLink WHERE user_id=? AND link=?",
(user_id, link))
db2.commit()
for row in cursor:
check_id = row["check_id"]
if check_id == 1:
return 1
else:
return 0
def database_insert(user_id, link):
db2 = sqlite3.connect("checkLink.db")
db2.execute("INSERT INTO checkLink(user_id, link, join_link, check_id)
VALUES (?,?,?,?)", (user_id, link,
"http://my link", 1))
db2.commit()
#route('/<link>/<chat_id>')
def index(link, chat_id):
check = database(chat_id, link)
if check != 1:
database_insert(chat_id, link)
redirect("https://my link")
#route('/redirect')
def index():
redirect("https://my link")
#route('/check/<link>/<chat_id>')
def index(link, chat_id):
check = database(chat_id, link)
if check == 1:
return {"id": chat_id, "permission": "True"}
else:
return {"id": chat_id, "permission": "False"}
run(host='my ip', port=my port)

Resources