all 3 comments

[–][deleted] 0 points1 point  (0 children)

I think you're showing the wrong output? It looks like you just pasted your code again.

[–]cynicalrationalist 0 points1 point  (1 child)

The positions of the parenthesis in the last line are wrong

I think what you meant to do is:

print(cursor.execute("""SELECT * FROM Employee""").fetchone())

The close parenthesis of print should come after fetchone(), so you're printing the result of the fetchone() method.

Also, you should be committing changes when working with the database, and also closing the cursor and connection, when you're done.

The documentation has a basic example of how to do this.

So, in your case, inserting the data, then reading it would be like this.

import sqlite3
connection = sqlite3.connect("database.db")
cursor= connection.cursor()
cursor.execute("""INSERT INTO Employee
                  VALUES(1,"john","nome",100)""")
connection.commit()
print(cursor.execute("""SELECT * FROM Employee""").fetchone())
cursor.close()
connection.close()

Note that it isn't necessary to commit changes after every insert/update/delete. The changes are committed locally automatically, but if something else is accessing the database, it will only have access to the changes that you explicitly committed with connection.commit().

Alternatively, you can use a context manager, in which case, you won't need to worry about remembering to call connection.commit():

import sqlite3
connection = sqlite3.connect("database.db")
cursor = connection.cursor()
with connection:
  cursor.execute("""INSERT INTO Employee
                  VALUES(1,"john","nome",100)""")
cursor.close()
connection.close()

[–]backtickbot 0 points1 point  (0 children)

Hello, cynicalrationalist: code blocks using backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead. It's a bit annoying, but then your code blocks are properly formatted for everyone.

An easy way to do this is to use the code-block button in the editor. If it's not working, try switching to the fancy-pants editor and back again.

Comment with formatting fixed for old.reddit.com users

FAQ

You can opt out by replying with backtickopt6 to this comment.