I am using this below code to update the records of my table but it doesn't work and it doesn't update my table
conn = mysql.connector.connect(host='localhost',
database='rps',
user='root',
password='')
cur = conn.cursor()
cur.execute("""UPDATE players SET score=%s WHERE chat_id =%s""", (int(self.p1.score), str(self.p1.chat__id)))
cur.execute("""UPDATE players SET score=%s WHERE chat_id =%s""", (int(self.p2.score), str(self.p2.chat__id)))
conn.commit()
cur.close()
conn.close()
It is completely true but i don't know how to solve this problem
Can you help me to solve it guys ?
Thanks
You can set try/catch on your query execution:
try:
cursor.execute(some_statement)
except MySQLdb.IntegrityError, e:
# handle a specific error condition
except MySQLdb.Error, e:
# handle a generic error condition
except MySQLdb.Warning, e:
# handle warnings, if the cursor you're using raises them
If you don't catch any exceptions, you should check your program logic.
Related
So I have a python file that has a connection to a MariaDB server. The connection works, so that is not the problem. Select, Deletes and so on work, but when I tried the Alter statement to reset the auto-increment, the "cursor.execute" statement would freeze my program. This is my code:
def ResetAutoIncrement_MariaDB(table):
connect_MariaDB()
try:
statement = ("ALTER TABLE %s AUTO_INCREMENT = 1" % (table))
cursor.execute(statement)
except mariadb.Error as e:
print(f"Error: {e}")
conn.commit()
conn.close()
So when I execute the following function for example, my code would freeze when it reached the "cursor.execute(statement)" in the "ResetAutoIncrement_MariaDB(table)" function above.
def deleteWholeTable_MariaDB(table):
connect_MariaDB()
try:
statement = ("DELETE FROM %s" % (table))
cursor.execute(statement)
ResetAutoIncrement_MariaDB(table)
except mariadb.Error as e:
print(f"Error: {e}")
conn.commit()
conn.close()
The DELETE in this function works, but the other function doesn't. Any suggestions? Thanks!
def connect_MariaDB():
try:
global conn
conn = mariadb.connect(
user="user",
password=USERPASSWORD,
host="192.168.76.3",
port=3306,
database="Discord_Bots"
)
except mariadb.Error as e:
print(f"Error connecting to MariaDB Platform: {e}")
sys.exit(1)
# Get Cursor
global cursor
cursor = conn.cursor()
there’s something wrong in my python script: when I try to put some data in my database and print it, it looks like it’s working, but when I rerun the code, or if I check the phpmyadmin, there’s no data saved in the db. Does anyone have some idea on how to solve this problem?
import mysql.connector
from mysql.connector import errorcode
def connect():
""" Connect to MySQL database """
try:
conn = mysql.connector.connect(host='localhost',
database='Temperature',
user='Temperature',
password='mypass')
if conn.is_connected():
print('Connected to MySQL database')
cur = conn.cursor()
query = "INSERT INTO Temp(temp, humi) " \
"VALUES(315, 55)"
try:
cur.execute(query)
except MySQLdb.ProgrammingError as e:
print(e)
query = "SELECT * FROM Temp"
try:
cur.execute(query)
for reading in cur.fetchall():
print (str(reading[0])+" "+str(reading[1]))
except MySQLdb.ProgrammingError as e:
print(e)
except Error as e:
print(e)
finally:
conn.close()
if __name__ == '__main__':
connect()
You will need to add conn.commit() before conn.close(). That should solve the problem.
I've got psycopg2 running and I can successfully query tables of my database. This is a working example of querying the table my_table:
import psycopg2
try:
conn_string="dbname='my_dbname' user='user' host='localhost' password='password'"
print "Connecting to database\n->%s" % (conn_string)
conn = psycopg2.connect(conn_string)
print "connection succeeded"
except:
print "no connection to db"
cur = conn.cursor()
try:
cur.execute(""" SELECT * from my_table; """)
records = cur.fetchall()
cur.close()
except:
print "Query not possible"
Question: How can I query a view, let it be called my_view, within the same database my_dbname?
The same way you'd query a table. From a SELECT point of view, a VIEW is the exact same thing as a TABLE:
cur.execute("SELECT * from my_view")
Note that you generally do not want to use a black except:. Catch a specific exception if you have to, but you are usually better off not catching the exception at all rather than block all feedback on errors as you've done here.
I am accessing a MySQL database from python via MySQLdb library. I am attempting to test the database connection as shown below.
db = MySQLdb.connect(self.server, self.user,
self.passwd, self.schema)
cursor = db.cursor()
try:
cursor.execute("SELECT VERSION()")
results = cursor.fetchone()
ver = results[0]
if (ver is None):
return False
else:
return True
except:
print "ERROR IN CONNECTION"
return False
Is this the right way one should test the connectivity when writing unit testcases? If there is a better way, please enlighten!
I could be wrong (or misinterpreting your question :) ), but I believe that a connection-related exception gets thrown on MySQLdb.connect(). With MySQLdb, the exception to catch is MySQLdb.Error. Therefore, I would suggest moving the db setup inside of the try block and catching the proper exception (MySQLdb.Error). Also, as #JohnMee mentions, fetchone() will return None if there are no results, so this should work:
try:
db = MySQLdb.connect(self.server, self.user, self.passwd, self.schema)
cursor = db.cursor()
cursor.execute("SELECT VERSION()")
results = cursor.fetchone()
# Check if anything at all is returned
if results:
return True
else:
return False
except MySQLdb.Error:
print "ERROR IN CONNECTION"
return False
If you don't care about the connection and are just looking to test the execution of the query, I guess you could leave the connection setup outside the try but include MySQLdb.Error in your exception, perhaps as follows:
db = MySQLdb.connect(self.server, self.user, self.passwd, self.schema)
cursor = db.cursor()
try:
cursor.execute("SELECT VERSION()")
results = cursor.fetchone()
# Check if anything at all is returned
if results:
return True
else:
return False
except MySQLdb.Error, e:
print "ERROR %d IN CONNECTION: %s" % (e.args[0], e.args[1])
return False
This would at least give you a more detailed reason of why it failed.
Yes. Looks good to me.
My personal preferences:
actually throw an exception if no connection
you only need to fetchone, the test for None is superfluous (unless you're keen to enforce a minimum version of the database)
The following cx_Oracle code works fine when the database is up:
#!C:\Python27
import cx_Oracle
try:
conn = cx_Oracle.connect("scott/tiger#oracle")
try:
curs = conn.cursor()
curs.execute("SELECT dummy FROM sys.dual")
print curs.fetchone()[0]
finally:
curs.close()
finally:
conn.close()
But if the database happens to be down when I run this script, a NameError is raised:
Traceback (most recent call last):
File "C:\Users\ArtMetzer\Documents\Code\Python\db_conn_test.py", line 14, in <module>
conn.close()
NameError: name 'conn' is not defined
This makes sense to me: cx_Oracle wasn't able to instantiate a connection, so the variable conn never got set, and hence has no close() method.
In Python, what's the best way to ensure your database connection closes, while still gracefully handling the condition of a down database?
Doing something like the following seems like a massive kludge to me:
finally:
try:
conn.close()
except NameError:
pass
You can try initializing conn to something like None before-hand and testing that in the finally block. This works because the only place the connection is set to something else is when it is opened. So opened implies non-None and None implies not-opened:
#!C:\Python27
import cx_Oracle
conn = None
try:
conn = cx_Oracle.connect("scott/tiger#oracle")
try:
curs = conn.cursor()
curs.execute("SELECT dummy FROM sys.dual")
print curs.fetchone()[0]
finally:
curs.close()
finally:
if conn is not None:
conn.close()
According to the docs, you don't really need to bother closing the connection:
https://cx-oracle.readthedocs.io/en/latest/user_guide/connection_handling.html#closing-connections
The important line being:
Alternatively, you may prefer to let connections be automatically cleaned up when references to them go out of scope. This lets cx_Oracle close dependent resources in the correct order.
(not exactly an answer, but comments don't have nice formatting)
Try this:
#!C:\Python27
import cx_Oracle
try:
conn = cx_Oracle.connect("scott/tiger#oracle")
try:
curs = conn.cursor()
curs.execute("SELECT dummy FROM sys.dual")
print curs.fetchone()[0]
finally:
curs.close()
conn.close()
except Exception as e:
print e
Not ideal, but should work better. I'm also wondering why so much nesting. Why not do this:
#!C:\Python27
import cx_Oracle
try:
conn = cx_Oracle.connect("scott/tiger#oracle")
curs = conn.cursor()
curs.execute("SELECT dummy FROM sys.dual")
print curs.fetchone()[0]
curs.close()
conn.close()
except Exception as e:
print e
BTW, I have this assumption that the connection and the cursor will close automatically on exit, removing the need to close them explicitly.