Writing to MySQL using Python is not working? - python

I have this simple code for writing data to MySQL database.
mycursor = sql_db.cursor()
sql = "INSERT INTO users (discord_id, platform, gamertag) VALUES (%s, %s, %s)"
val = (interaction.user.id, platform.value, gamertag)
print(val)
try:
mycursor.execute(sql, val)
sql_db.commit
except mysql.connector.Error as err:
print(err)
print("Error Code:", err.errno)
print("SQLSTATE:", err.sqlstate)
print("Message:", err.msg)
mycursor.close
sql_db.close
print(mycursor.rowcount, "record inserted.")
MySQL server is hosted on VPS server
enter image description here
Console output is:
(176432554692313088, 'acti', 'jcK_#2039728')
1 record inserted.
Looks like writing was successful, but my database is still empty. Any idea what is happening or how to catch error to find out why my data are not writing to database?
I tried catch errors with this except but as you can see, it doesn't catch anything.
except mysql.connector.Error as err:
print(err)
print("Error Code:", err.errno)
print("SQLSTATE:", err.sqlstate)
print("Message:", err.msg)

Related

Python Reset Auto Increment on MariaDB table not working

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()

Problem putting using %s in a MySQL command

I'm trying to automate (by using python scripting) the ability to create a MySQL role, but for some reason I am unable to put my string variable into mysql command. This is what I've got so far:
#!/usr/bin/python3
import mysql.connector
from mysql.connector import errorcode
# Open database connection
try:
serverHostName='localhost'
userName='root'
passwd='password'
databaseName='mysql'
roleName='reader'
cnx = mysql.connector.connect(
host=serverHostName,
database=databaseName,
user=userName,
password=passwd)
cursor=cnx.cursor(prepared=True)
dropRole="""DROP ROLE IF EXISTS %s """
print(dropRole, roleName)
#cursor.execute(dropRole, roleName)
#cnx.commit()
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
cnx.close()
print("You have successfully disconnected from your MySQL database")
what comes out is the following:
DROP ROLE IF EXISTS %s reader
You have successfully disconnected from your MySQL database
If anyone can explain to me why %s and the reader is showing up in my print line that would be much appreciated.
You didn't call a formatting operator to subsitute roleName into the string, so it's just printing the format string. Use the % operator to perform formatting.
print(dropRole % roleName)

MySQL remote query works, but remote insert fails via Python

I'm running Ubuntu 16.04 with MySQL. I've opened the MySQL server for remote connections, and my remote Python script can query my database, but all attempts to INSERT fail without any error log entry.
It also looks like my remote INSERTs are being seen, because my AUTO_INCREMENT ID increases without entries being made when I run the Python INSERT code.
Any insight is appreciated!
Simple table schema:
CREATE TABLE test (
ID int NOT NULL AUTO_INCREMENT,
x INT,
PRIMARY KEY (ID)
);
This works directly on the server:
INSERT INTO test (x) VALUES (10);
This is the Python query that's working:
try:
connection = db.Connection(host=HOST, port=PORT, user=USER, passwd=PASSWORD, db=DB)
cursor = connection.cursor()
print("Connected to Server")
cursor.execute("SELECT * FROM test")
result = cursor.fetchall()
for item in result:
print(item)
except Exception as e:
print('exception connecting to server db: ' + str(e))
finally:
print('closing connection...')
connection.close()
And the Python INSERT that's not working:
try:
connection = db.Connection(host=HOST, port=PORT, user=USER, passwd=PASSWORD, db=DB)
cursor = connection.cursor()
print("Connected to Server")
cursor.execute("INSERT INTO test (x) VALUES (10);")
except Exception as e:
print('exception connecting to server db: ' + str(e))
finally:
print('closing connection...')
connection.close()
Thanks
Add this line after the execute() call:
cursor.execute("INSERT INTO test (x) VALUES (10)")
connection.commit()
When making changes to the db, it is required that you commit your changes, no change(s) would take effect.

Python don't register in MySQL server

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.

AttributeError: 'MySQLCursor' object has no attribute 'commit'

def fillblast(sequentie, titel_lijst, score_lijst, e_lijst, iden_lijst, pos_lijst, gaps_lijst):
conn = mysql.connector.connect(host = "ithurtswhenip.nl", user = "pg2", password = "pg2", database= "pg2", port= "3307")
cursor = conn.cursor()
Blast = 1000
for i in range(0,len(titel_lijst)):
Blast =+ 2
cursor.execute("INSERT INTO `pg2`.`Blast` (`Blast_id`, `Blast_seq`, `Blast_titel`, `Blast_score`, `Blast_E`, `Blast_gaps`, `Blast_pos`, `Blast_iden`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s);", (Blast, sequentie[i] ,titel_lijst[i], score_lijst[i], e_lijst[i], iden_lijst[i], pos_lijst[i], gaps_lijst[i]))
print("1 record toegevoegd")
cursor.commit()
cursor.close()
conn.close()
I get the following error:
AttributeError: 'MySQLCursor' object has no attribute 'commit'
How does it come, and where does it go wrong?
I try to connect with MySQLWorkbench.
EDIT:
Now I get the following error:
mysql.connector.errors.DatabaseError: 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
Because you can not commit a cursor! you must commit the connection.
# cursor.commit() --> This is wrong!
conn.commit() # This is right
Check the docs...
While fixing some legacy code (that apparently hasn't been working for a couple of years, so users stopped trying to use it), we ran into the same error, using the MySQL-python package in Django. Using the suggestions on this and other answers however resulted in a different error, on account of it occurring within the Django ORM:
django.db.transaction.TransactionManagementError: This code isn't
under transaction management
So for those who run into this error after using conn.commit() instead of cursor.commit(), you may be able to use enter_transaction_management and leave_transaction_management (note that this was for Django 1.4.6 and MySQL-python 1.2.5; I may have to update this once we get the Django upgrade completed):
try:
conn.enter_transaction_management()
cursor = conn.cursor()
cursor.execute(sql)
conn.commit()
except DatabaseError as e:
cursor.rollback()
log.warning('log warning here')
# Handle other exceptions here.
finally:
if cursor:
cursor.close()
conn.leave_transaction_management()

Categories

Resources