python Mysql Delete - python

I am new to MYSQL and i am facing a very easy problem with MYSQL. I am creating a database that contains a school table , this table contains the sschool's name , contact, address, ID( primary key) . I need to delete a record based on the user's choice of id ( call this variable school_id) , so how to write this in a mysql statement using python ? i have tried this but i know it is wrong -->
print "Delete school"
school_id = int(input('Please, enter an ID: '))
cursor.execute("DELETE FROM `schools` WHERE id = %s", (school_id,))
its no deleting.whats the error

Have you committed the delete?
cursor.commit()

As already said by joof most likely you haven't commited the change.
If it doesn't help I'd try first to execute this statment in mysql and see if it works, then check if you have right connection to your db.
Link to using sql in Python.
https://docs.python.org/3.6/library/sqlite3.html

Unless you commit, it won't be executed:
cursor.commit()
Have fun.

print "Delete school"
school_id = int(input('Please, enter an ID: '))
cursor.execute("DELETE FROM `schools` WHERE id = %s", (school_id,))

From MySQL documentation on commit:
it is important to call this method after every transaction that modifies data for tables that use transactional storage engines.
You don't have to use it after literally every transaction - it's enough if you call it once after all execute are called:
def a():
cursor.execute('insert ...') # cursor object
cursor.execute('update ...')
connection.commit() # connection object
def b():
cursor.execute('delete ...')
connection.commit()

Related

delete row for sqlite3 use WHERE condition

I have some problems use DELETE function in sqlite3 I try to delete a row from some tables by passing the name of the table using .formt like that :
def delete_record_from_table(self, table_name, username):
self.cur.execute("DELETE FROM {} WHERE username =?".format(table_name), (username,))
there is no problem with the ran it not return an error but when I print the table the row wasn't delete
if I pass the real name of the table the row delete
For deletes and inserts, you have to commit the connection object used to create the cursor object by running conn.commit()
Here's a link on how to use connection
Also be sure to close your connection when you're finished

Where is the place that discord bots can store information [discord.py]

I am not too new to python but new to discord.py. I have tried to go through the discord.py manual but did not find where I can store some temporary variable on a discord bot.
discord.py manual: http://discordpy.readthedocs.io/en/latest/api.html
For example, in PHP SESSION, we can store information on the SESSION(). Did discord.py has the same kind of things?
For example, if we have user "A" and user "B". "A" will be stored as an object of "A_Object", such as messages etc. Similar for "B_Object" but will be different from "A_Object". In discord.py, is there a function like that?
Thank you so much for the help!
You can use sqlite database. Write inside your def:
# define database
import sqlite3
conn = sqlite3.connect("my_database.db")
cursor = conn.cursor()
# get stored object from database
sql = "SELECT * FROM my_table WHERE field_1=?"
cursor.execute(sql, [(value_1)])
data = cursor.fetchall()
# if object does not exist, create it
if len(data) == 0:
sql = "INSERT INTO my_table VALUES (?, ?)"
cursor.execute(sql, [(value_1), (value_2)])
# if stored object exist and we need update it
elif ...:
sql = "UPDATE my_table SET field_2 = ? WHERE field_1 = ?"
cursor.execute(sql, [(value_2), (value_1)])
else:
# get data from first object
value_of_field_1 = data[0][0]
# get data from third object
value_of_field_2 = data[2][1]
# close database connection
conn.commit()
conn.close()
my_database.db - is a sqlite db file and should be stored in sa same folder with bot's .py file.

Python: How to access MySQL DB table using SQLAlchemy

I am making a python GUI that will look up the the status of a helpdesk ticket in a MySQL database. I connected python to an existing MySQL database with SQLAlchemy using the code below.
conn = mysql.connector.connect(user='root',
password='stuff',host='127.0.0.1',
database='mydb')
c = conn.cursor()
I only need access to one of the columns, ticket_id, in a table called tickets. Basically I want to do this:
SELECT ticket_status FROM tickets WHERE ticket_id = 123;
What would be simplest way to do this?
The following code should work at fetching a single value. If you realize later you need to fetch more than one value you can change fetchone() to fetchall()
try:
sql = '''
SELECT ticket_status FROM tickets WHERE ticket_id = 123
'''
c.execute(sql)
result = c.fetchone()
except Exception as e:
raise Exception(e)

SQL update command with python not working

I'm having an issue getting my python script to update my sqlite db.
The first part seems to work fine:
conn = sqlite3.connect('/Users/test/Desktop/my-accounts.db')
currentAccount = None
for row in conn.execute('SELECT email FROM accounts WHERE active=0'):
currentAccount = row[0]
print "Checking out: ",currentAccount
break
if currentAccount is None:
print "No available accounts"
Then this next part I want to take the variable currentAccount and update the row in the db where that value is.
else:
conn.execute('UPDATE accounts SET active=1 WHERE email=?', [currentAccount,])
conn.close()
I don't get any errors in the console but the db does not update. The email column is a VARCHAR and the active column is an INT.
Thanks.
SOLUTION was to add
conn.commit() after execute()
try to add conn.commit() after conn.execute("XXX"). Sometimes sqlite3 doesn't auto commit the execution.

UPDATE and INSERT don't work in Python

I use this code to retreive an id. It works:
db = MySQLdb.connect("localhost","root","","proyectoacademias" )
cursor = db.cursor()
sql = "SELECT id FROM test WHERE url=\'"
sql = sql + self.start_urls[0]
sql = sql + "\'"
cursor.execute(sql)
data = cursor.fetchone()
for row in data:
self.id_paper_web=str(row)
db.close()
It gives me the id of the current row I have to update...
But then I try to update or to insert, it doesn't work....
def guardarDatos(self):
db = MySQLdb.connect("localhost","root","","proyectoacademias" )
cursor = db.cursor()
sql = "UPDATE test SET abstract=\'"+str(self.abstracto)+"\', fecha_consulta=\'"+str(self.fecha_consulta)+"\', anio_publicacion=\'"+str(self.anio_publicacion)+"\', probabilidad="+str(self.probabilidad)+" WHERE id = "+str(self.id_paper_web)
print "\n\n\n"+sql+"\n\n\n"
cursor.execute(sql)
for i in range (len(self.nombres)):
sql = "INSERT INTO test_autores VALUES (\'"+self.nombres.keys()[i]+"\', "+str(self.id_paper_web)+", \'"+self.instituciones[self.nombres[self.nombres.keys()[i]]]+"\', "+str((i+1))+")"
print "\n\n\n"+sql+"\n\n\n"
cursor.execute(sql)
db.close()
I print every sql query I sent and they seem to be fine... no exceptions thrown, just no updates or inserts in the database...
you must commit ... or set the db to auto commit
db.commit()
lots of py sqlite3 tutorials out there
By default, the sqlite3 module opens transactions implicitly before a
Data Modification Language (DML) statement (i.e.
INSERT/UPDATE/DELETE/REPLACE), and commits transactions implicitly
before a non-DML, non-query statement (i. e. anything other than
SELECT or the aforementioned).
So if you are within a transaction and issue a command like CREATE
TABLE ..., VACUUM, PRAGMA, the sqlite3 module will commit implicitly
before executing that command. There are two reasons for doing that.
The first is that some of these commands don’t work within
transactions. The other reason is that sqlite3 needs to keep track of
the transaction state (if a transaction is active or not).
You can control which kind of BEGIN statements sqlite3 implicitly
executes (or none at all) via the isolation_level parameter to the
connect() call, or via the isolation_level property of connections.
If you want autocommit mode, then set isolation_level to None.
Otherwise leave it at its default, which will result in a plain
“BEGIN” statement, or set it to one of SQLite’s supported isolation
levels: “DEFERRED”, “IMMEDIATE” or “EXCLUSIVE”.
http://docs.python.org/library/sqlite3.html Section 11.13.6

Categories