Python on the Train because "I shall not be there; I shall rise and pass." (Database Operations)
Python on the Train because "I shall not be there; I shall rise and pass." (Database Operations)
One of the nice things about having had 15 years of intense seizures is that nobody can say quite like me that when they fall, they pick themselves up again.
Someone said it to me about 7 years ago, when they were at their worst (how was that already 7 years ago? How?). I thought they were so annoying. But like many people who were right at the time I have come to learn and recognise the value of their words later. So it's always worth listening to people who are older and wiser. They know a thing or two.
I can pretty much say that I am a world expert at picking myself up now. An absolute, worldwide, world-class expert. This is really useful. It's good for picking yourself up in all kinds of situations.
Quadruple rainbow it was 10x brighter |
Committing Changes and Closing the Database Connection
I have learned how to create, insert, edit, and pull data from an SQLite Database.
One of the most important methods however is to commit your changes to the SQLite database.
This can be achieved via the .commit() method. To save any alterations to the database.
You normally have to call .commit() on the connection, I think. Whereas most of the other methods have been called on the cursor. But again this makes sense.
The cursor is just the little thingy that travels back and forth between the two. (Python and the DB).
Finally, we close the connection by using connection.close().
Here is some code that I wrote for practising this:
from start import helper
helper()
import sqlite3
con = sqlite3.connect("titanic.db")
curs = con.cursor()
# insert a row in new_table table
curs.execute("""INSERT INTO new_table VALUES ('Stephanie Bready', 37, 'stephB423', 30.)""")
# commit this change
con.commit()
# close the connection
con.close()
curs.execute()
And here is the code for the review section of the lesson:
# import module sqlite3
import sqlite3
# Create connection object
con = sqlite3.connect("titanic.db")
# Create cursor object
curs = con.cursor()
# retrieve the row where `username = 'stephB423';` from new_table
n_row = curs.execute('''SELECT * FROM new_table WHERE username = 'stephB423';''').fetchall()
print(n_row)
# close the connection
con.close()
Next up is hard to decide - the flow is the project but they normally do a quiz after the lesson.
So just a revision - the steps are
- Import sqlite3
- Create a connection on sqlite3
- AND PUT THE NAME OF THE DB IN!!! oops
- Create a cursor on the connection
- Execute on the cursor
- fetch on the cursor
- Commit on the connection
- Close the connection
- If you try and execute on the cursor again after that: "sqlite3.ProgrammingError: Cannot operate on a closed database."
NOW I AM COMPLETING THE HUGE PROJECT. ❤️
Comments
Post a Comment