Python Forum

Full Version: Basic SQL query using Py: Inserting or querying sqlite3 database not returning data
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, can someone assist here please:
When I run the program below, I expect table to be created and record inserted into the database.
However when I query database, it displays no records.

Please let me know if you can point out what is missing here from either query or insert operation.

Thank you,
Marlon

=====
import sqlite3
def insert():


	connection_obj = sqlite3.connect('apix.db')
	cursor_obj = connection_obj.cursor()
	cursor_obj.execute("DROP TABLE IF EXISTS APIX")
	table = """ CREATE TABLE APIX (
				IP VARCHAR(255) NOT NULL,
				DATE CHAR(8) NOT NULL
			); """
	
	cursor_obj.execute(table)
	print("Table is Ready. Now I will insert...")
	connection_obj.execute ("""INSERT INTO APIX (IP,Date) VALUES ("1.1.1.1","03/03/01")""")
	connection_obj.close()


def query():

	connection_obj = sqlite3.connect('apix.db')
	cursor_obj = connection_obj.cursor()
	statement = '''SELECT * FROM APIX'''
	cursor_obj.execute(statement)
	output = cursor_obj.fetchall()
	for row in output:
  		print(row)
  
	connection_obj.commit()
	connection_obj.close()
	return output

insert()
print(query())
(venv) user@3c0630078aad venv % python delmain.py
Table is Ready. Now I will insert...
[]
(venv) user@3c0630078aad venv %
Please use proper bbcode when posing to keep the format.
You need to commit in the insert() (i.e. after changing the DB - CREATE, INSERT, etc.) , not in query() (i.e. SELECT - what do you commit after selecting?)
My bad, once I posted, I verified the commit in the wrong code block. Thanks all for the replies.