ulogin=str(self.t1.get())
med=str(self.mymed.get("1.0",END))
print(med)
conn = connect("med.db")
c = conn.cursor()
c.execute("UPDATE user_details SET reminder ="+ med +"WHERE username =" + ulogin)
conn.commit
conn.close()
im trying to get this to update a text wall however it breaks continuously
line 284 on GitHub
link: https://github.com/Polar001/medicine-reminder/commit/0f6e74a1103937a24c67af3e8f07a2bcf0975f0a
if possible be as basic as possible im not good at coding at all
Your SQL statement is incorrectly constructed, use placeholder as below:
c.execute("UPDATE user_details SET reminder = ? WHERE username = ?", (med, ulogin))
Related
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
I'm trying to update user credentials for PostgreSQL db user using Python. I've tried referring to the following thread but that doesn't seem to solve my issue unfortunately:
How to change password of a newly created user using variable in postgresql 9.5 SP
Here's my code:
con = p.connect(database="mydB", user="abc", password="testing", host="127.0.0.1", port="5432")
cur = con.cursor()
uid = "adi"
pwd = "test6"
statement = statement = '''CREATE or REPLACE FUNCTION add_user ({}, {}) RETURNS void AS $$ EXECUTE ALTER USER ' || $1 || ' WITH PASSWORD || $2||'''.format(uid,pwd)
cur.execute( statement)
cur.execute('''COMMIT''')
I get the following error:
ProgrammingError: syntax error at or near "'adi'"
Please help or refer me to a thread with a better solution. Thanks in advance, everyone!
error image
I was able to solve this successfully.
import psycopg2 as p
con = p.connect(database="mydB", user="adi", password="xxxx", host="127.0.0.1", port="5432")
cur = con.cursor()
uid = "adi"
pwd = "test"
statement = '''ALTER USER {} WITH PASSWORD %s '''.format(uid)
cur.execute(statement, [pwd])
cur.execute('''COMMIT''')
Try to give the username and password in the actual statement and try executing.
First try removing the extra quotation before ALTER USER and execute.
If doesn't work try this:
statement = '''CREATE or REPLACE FUNCTION add_user ({}, {}) RETURNS void AS $$ EXECUTE 'ALTER USER ' || $1 || ' WITH PASSWORD || $2||'''.format(uid,pwd)
cur.execute(statement)
I hope my formatting is OK as this is my first time using stackOverflow
No matter how I change my code and methods I keep on getting the same bug when executing this code
File "/usr/lib/python3/dist-packages/mysql/connector/cursor.py",
line 83, in call
return bytes(self.params[index]) IndexError: tuple index out of range
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "sqlTest.py", line 40, in
mycursor.execute(sql,val) File "/usr/lib/python3/dist-packages/mysql/connector/cursor.py", line 558,
in execute
stmt = RE_PY_PARAM.sub(psub, stmt) File "/usr/lib/python3/dist-packages/mysql/connector/cursor.py", line 86,
in call "Not enough parameters for the SQL statement")
mysql.connector.errors.ProgrammingError: Not enough parameters for the
SQL statement
This is a section of my main project that would log the current values of certain Variable as well as the GPS Coordinates and a timestamp.
From what I've seen the main issue has to do with the database expecting 8 database entries when I should only need 7.
I mainly followed https://www.w3schools.com/python/python_mysql_insert.asp tutorial as I am not super familiar with using python and mySQL together.
#Initialize mySQL databse connection
mydb = mysql.connector.connect(
host="themySQLserver.net",
user="myUSername",
passwd="_____",
database="24totheTLE"
)
These variables are normally set by the main program but I manually set them for troubleshooting
top_since_epoch = 4
left_since_epoch = 1
bottom_since_epoch = 5
right_since_epoch = 3
This is the code that calls the python2 script to get the gps data
fullgps = os.popen("python gps.py").read()
gps_split = fullgps.split(";")
gps_split[1] = gps_split[1].rstrip()
s1 = float(gps_split[0])
s2 = float(gps_split[1])
The primary key "LogNum" for my database is set to auto increment and as such I have not mentioned it in my code.
ts = time.time()
timestam = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
mycursor = mydb.cursor()
sql = "INSERT INTO records (TimeStamp,CarsTop,CarsLeft,CarsRight,CarsBottom,GPSLong,GPSLat) VALUES (%s, %s, %s, %s, %s, %s, %s)"
val = [timestam,top_since_epoch,left_since_epoch,bottom_since_epoch,s2,s1]
mycursor.execute(sql,val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
Thanks to anyone who replies.
Finally found the answer
The problem was that the code I used to pass the date-time information was not set up to interact with the "mysql.connector" This was solved by updating the code to work with MySQLdb libaries:
This code Worked for me
#Initialize mySQL databse connection
mydb = MySQLdb.connect(
host="sql24.cpt1.host-h.net",
user="stonesp_1",
passwd="______",
database="24totheTLE"
)
print("5 minutes")
fullgps = os.popen("python gps.py").read()
gps_split = fullgps.split(";")
s1 = float(gps_split[0])
s2 = float(gps_split[1])
print(s1)
print(s2)
ts = time.time()
timecur = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
print(timecur)
mycursor = mydb.cursor()
sql = "INSERT INTO records (TimeStamp,CarsTop,CarsLeft,CarsRight,CarsBottom,GPSLong,GPSLat) VALUES (%s,%s,%s,%s,%s,%s,%s)"
val = [timecur,top_since_epoch,left_since_epoch,right_since_epoch,bottom_since_epoch,s2,s1]
mycursor.execute(sql,val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
mydb.close()
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.
First and foremost, I must admit I am new to Python and SQL. Now, I will get the problem. I am trying to update a table where column_ID is equivalent to a variable. In the Python class I have a function with the following statement:
stName = self.txtName.text()
stUsername = self.txtUsername.text()
stPassword = self.txtPassword.text()
stMobile = self.txtMobile.text()
myID = self.txtID.text()
sql_update_query = """UPDATE signup SET name = %s, username = %s, password = %s, mobile = %s WHERE id = myID"""
input = (stName, stUsername, stPassword, stMobile)
curs.execute(sql_update_query, input)
conn.commit()
When I click the Update button to run this function, the system prompts 'Python has stopped working'.
Can someone assist me to fix the SQL statement?
myID needs to be passed as an argument to the sql statement.
sql_update_query = """UPDATE signup SET name = %s, username = %s, password = %s, mobile = %s WHERE id = %s"""
And
input = (stName, stUsername, stPassword, stMobile, myID)