delete row for sqlite3 use WHERE condition - python

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

Related

MariaDB - Inserting Values doesn't affect any rows

I want to insert given values from my docker app-service to the MariaDB-service.
The connection has been established because I can execute SELECT * FROM via the MariaDB.connection.cursor.
First of all I create the connection:
def get_conn() -> mariadb.connection:
try:
conn = mariadb.connect(
user="XXX",
database="XXX",
password="XXX",
host="db",
port=33030,
)
except mariadb.Error as e:
print(f'Error connecting to MariaDB Platform: {e}')
sys.exit(1)
return conn
Then I create a mariadb.connection.cursor-Object:
def get_cur() -> mariadb.connection.cursor:
conn = get_conn()
cur = conn.cursor()
return cur
Finally I want to insert new values in the table testing:
def write_data():
cursor = get_cur()
conn = get_conn()
cursor.execute('INSERT INTO testing (title) VALUE ("2nd automatic entry");')
print("Executed Query")
conn.commit()
cursor.close()
conn.close()
print("Closed Connection")
return True
To test, if the entries are inserted, I started with 1 manual entry, then executed the write_data()-function and to finish of I inserted a 2nd manual entry via the console.
After the procedure the table looks like:
Note that the ìd is on AUTO_INCREMENT. So the function write_data() was not skipped entirely, because the 2nd manual entry got the id 3 and not 2.
You're committing a transaction in a different connection than the one your cursor belongs to.
get_conn() creates a new database connection and returns it.
get_cur() calls get_conn, that gets it a new connection, retrieves a cursor object that belongs to it, and returns it.
In your main code, you call get_conn - that gives you connection A.
Then you obtain a cursor by calling get_cur - that creates a connection B and returns a cursor belonging to it.
You run execute on the cursor object (Connection B) but commit the connection you got in the first call (Connection A).
PS: This was a really fun problem to debug, thanks :)
It's really easy, in a new table with new code, to unintentionally do an INSERT without a COMMIT. That is especially true using the Python connector, which doesn't use autocommit. A dropped connection with an open transaction rolls back the transaction. And, a rolled-back INSERT does not release the autoincremented ID value for reuse.
This kind of thing happens, and it's no cause for alarm.
A wise database programmer won't rely on a set of autoincrementing IDs with no gaps in it.

python Mysql Delete

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

Trying to find last insert row ID; returned value is encrypted

I'm using pypyodbc with SQL Server 2016.
I am trying to insert and grab the last id inserted into database following another user's remarks but the returned value seems to be encrypted. Is there a way to decrypt it?
def executeSQL (command):
connection = pypyodbc.connect('Driver={SQL Native Client};'
'Server=blah\blah;'
'Database=Impact;'
'uid=Admin;pwd=F$sfgdfgs99')
cursor=connection.cursor()
cursor.execute(command)
id = cursor.execute("SELECT ##IDENTITY")
connection.commit()
connection.close()
return id
sqlexecute = 'INSERT INTO PERSONS([LastName], [FirstName]) VALUES(\''+lastname.encode('utf-8')+'\',\''+firstname.encode('utf-8')+'\');\n'
lastid = executeSQL(sqlexecute)
print lastid
Output:
<pypyodbc.Cursor instance at 0x000000000B870C88>
It is not encrypted, it is telling you the type of the object that this is an instance of. In this case, it is pypyodbc.Cursor.
To fetch the actual rows, you do id.fetchall() which will return a list of the results. You can then loop over them to read the contents.

MySQL not updating after calling connection.commit() with Flask (WORKING)

I'm using flask to build a simple web app but for whatever reason the conn.commit() is not committing the data into the database. I know this because when I manually add something to the database the data doesn't change but the ID section increases each time I test it (because its using auto increment). So basically my current table has ID 1, Username test, Password test and the next entry that I inserted manually (after trying to use my application) was ID 5, Username blah, Password blah. Is there any specific reason that the commit isn't working?
EDIT: I had to change cursor = mysql.connect().cursor() to conn.cursor()
#app.route('/add_data/')
def add_tv_to_database():
conn = mysql.connect()
cursor = mysql.connect().cursor()
cursor.execute("INSERT INTO _accounts VALUES (null, 'test','test')")
conn.commit()
return render_template('index.html')
In the fourth line of your code, change it from cursor = mysql.connect().cursor() to cursor = conn.cursor(). This will ensure that the cursor uses the existing connection to database (from the previous line of code), instead of creating a new MySQL connection.

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.

Categories