Psycopg2: cursor.execute is not working properly - python

So, I have the following code that inserts the data of an old database to a new one:
...
cur_old.execute("""SELECT DISTINCT module FROM all_students_users_log_course266""")
module_rows = cur_old.fetchall()
for row in module_rows:
cur_new.execute("""INSERT INTO modules(label) SELECT %s WHERE NOT EXISTS (SELECT 1 FROM modules WHERE label=%s)""", (row[0], row[0]))
...
The last line executes a query where labels are inserted into the new database table. I tested this query on pgAdmin and it works as I want.
However, when execute the script, nothing is inserted on the modules table. (Actually the sequences are updated, but none data is stored on the table).
Do I need to do anything else after I call the execute method from the cursor?
(Ps. The script is running till the end without any errors)

You forgot to do connection.commit(). Any alteration in the database has to be followed by a commit on the connection. For example, the sqlite3 documentation states it clearly in the first example:
# Save (commit) the changes.
conn.commit()
And the first example in the psycopg2 documentation does the same:
# Make the changes to the database persistent
>>> conn.commit()

As Evert said, the commit() was missing. An alternative to always specifying it in your code is using the autocommit feature.
http://initd.org/psycopg/docs/connection.html#connection.autocommit
For example like this:
with psycopg2.connect("...") as dbconn:
dbconn.autocommit=True

Related

sqlite commit not saving changes with update using python?

Description
I have a database that I already built in python3 utilizing sqlite. Up till this point, I have not had any issues with commit saving changes (with insert commands and delete commands). However, I am trying to utilize an update command and I have not been able to save the changes (it only changes the DB in the working memory despite calling commit().
The goal of this code snippet is to replace the null values in the database with an empty string as I have another function that cannot handle null data. I found a solution to do that here: Find null values from table and replace it with space - sqlite.
Details
Here is the current code that I am trying to execute:
self.cursor.execute(f'UPDATE {tbl_name} SET {col_name} = IFNULL({col_name}, "")')
self.conn.commit()
This code basically goes through the entire database one column at a time and replaces the null values.
Note that self is defined as follows:
Database.conn = sqlite3.connect(self.location + self.name)
Database.cursor = sqlite3.connect(self.location + self.name).cursor()
As earlier stated this correctly operates; however, it will not commit the changes to the actual database. This is verified by both DB browser for sqlite and pulling the data again on a close and re-execute.
I will also note that if I close out of this program and reinitialize it to run it again it will error out for the DB still being locked despite the last line of my code being:
Database.conn.commit() # Save (commit) the changes
Database.conn.close() # Close database
Conclusion
Thanks in advance as I have been beating my head against the wall with this one and have yet to find a problem like this elsewhere!
Your database connecton has nothing to do with your cursor.
You do
Database.conn = sqlite3.connect(self.location + self.name)
Database.cursor = sqlite3.connect(self.location + self.name).cursor()
So by creating a new connection for the cursor, a following Database.conn.commit() won't commit any changes you did with cursor.
Create your cursor like this to have the connection between connection and cursor:
Database.conn = sqlite3.connect(self.location + self.name)
Database.cursor = Database.conn.cursor()

How to insert data from one table into another table?

I'm new to python and I was trying to insert data from one table to another and the code is executing but it is not reflecting any changes in new table in which I want to insert data.
import mysql.connector
conn=mysql.connector.connect(user='root',password='',host='localhost',database='xyz')
mycursor=conn.cursor()
mycursor.execute("insert into newTable select * from oldTable group by mac,date,time order by mac")
I suppose it is because you are not committing the changes. Use the below code and see if it works.
conn.commit()
You need to use conn because that is the variable name for your connection to the database. A commit must be sent to the server, which in turn will commit your changes.
You need to add commit() to make the changes.
conn.commit()

Why doent SQLite save inserted data?

I always have to keep the SQL Insert statement in my python code in order to read the data from the database. Doesn't keeping the SQL insert statement in the python code amount to inserting same data multiple times into the database? I think the data insertion statement should be run once to insert data once, after which the data should be readable from the database. Whenever I omit the data insertion statement from my code, I am not able to read the data from the database, as though the script has not been run before.
Can someone please help me understand why this happens?
Below is the code:
#!/usr/bin/python
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully"
conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \ VALUES (1, 'Paul', 32, 'California', 20000.00 )")
conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \ VALUES (2, 'Allen', 25, 'Texas', 15000.00 )")
First point: you should use a cursor instead of calling connection.execute which is not part of the db-api2 standard.
So you want:
conn = sqlite3.connect('test.db')
c = conn.cursor()
c.execute(<your ssql statement here>)
Second point: nothing is really written to your db until you commit your transaction, so after your inserts you need :
conn.commit()
Note that all this is very clearly explained in the FineManual with a complete example, so please have mercy and read the doc before anything else.
Third point: your "test.db" file will be looked up (and eventually created if it does not exist) in whatever the current working directory is, so use an absolute path, always - because you cannot rely on where / how your script is called to be sure you're using the expected database.

How to commit a UPDATE in raw SQL in python

cursor = connection.cursor()
cursor.execute("UPDATE public.rsvp SET status=TRUE WHERE rsvp_id=%s", [rsvp_id])
cursor.execute("SELECT status, rsvp_id FROM public.rsvp WHERE rsvp_id=%s", [rsvp_id])
row = cursor.fetchall()
When I execute this in my Django project, I get the row returned as I expect to see it, but later when I select query for the same row, it appears as tho the statement was never really run. In my code, the column "status" defaults to NULL. After this is run, I still see NULL in my table.
You didn't specify what database you're dealing with, which may change the answer somewhat. However, with most database connections you need to finish with connection.commit() to really save changes on the database. This includes both update and insert operations. Failing to commit() usually results in a rollback of the actions.

MySQL rows delete when program exits

I'm using Python and MySQLdb to add rows to my database. It seems that when my script exits, the rows get deleted. My last lines before the script exits do a "select *" on the table, which shows my one row. When I re-run the script, the first lines (after opening the connection) do the same "select *" and return zero results. I'm really at a loss here. I've been working for about 2 hours on this, and can't understand what could be accessing my database.
Also, between running the scripts, I run the "select *" manually from a terminal with zero results.
If I manually add a row from the terminal, it seems to last.
The query to insert the row:
cursor.execute("INSERT INTO sessions(username, id, ip) VALUES (%s, %s, %s)", (username, SessionID, IP]))
The query I use to check the data:
cursor.execute("select * from sessions")
print cursor.fetchall()
This shows the row before the program exits, then shows nothing when the program is run again.
Thanks in advance for all the help.
Looks like you need to connection.commit() your changes after you execute the query (replace connection with your DB connection variable).
http://docs.python.org/library/sqlite3.html
Connection.commit():
This method commits the current transaction. If you don’t call this method, anything you did since the last call to commit() is not visible from other database connections. If you wonder why you don’t see the data you’ve written to the database, please check you didn’t forget to call this method.
Check this other question: Python MySQLdb update query fails
You can find some examples on how to commit, how to connect using autocommit, etc.

Categories

Resources