Friday, April 27, 2018

Querying a persisted SQLite using Python 3.7

Python uses the sqlite3 module written by Gerhard Häring. It provides a SQL interface compliant with the DB-API 2.0 specification described by PEP 249.

I launch the Python Shell in my All Programs.


PythonSQLite_00

Python 3.7.0b2 (v3.7.0b2:b0ef5c979b, Feb 28 2018, 01:32:48) [MSC v.1912 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.

Connecting to an existing SQLite database. UsersOwnerApr25.sqlite has a table called 'friends' with just one row of data.

 First you need to import sqlite3 and then establish a connection by providing the path to the database (note the direction of slashes).
---------------------
>>> import sqlite3
>>> conn=sqlite3.connect("C:/Users/Owner/Desktop/Blog2017/MSSS2017/SQLite3_DBS/UsersOwnerApr25.sqlite")
--------------------
After connecting create a cursor and the subsequently use the Execute() method of the cursor.

>>> c=conn.cursor()
>>> conn.commit()
-----------------------------------------------
For example, for inserting data into 'friends' table use the following statement. I already had a table with the name 'friends'
----------------------------------
>>> c.execute("Insert Into friends values('Jay', 'Kris',45)")

--This is something I need to figure out---

I try to print the results but I get the same response after the print() statement.
--------------------------------------
>>> y= c.execute('Select * from friends')
>>> print (y)

-----------------------------------------


Now I modify the print() statement and I succeed in printing the first row using the fetchone()method.
---------------------------------------
>>> print(c.fetchone())
('John', 'Chiavetta', 35)
-----------------------------
I print all the rows using the fetchall().
-----------------------------
>>> for row in c.execute('Select * from friends'):
print(row)
('John', 'Chiavetta', 35)
('Jay', 'Kris', 45)
>>>
-------
I have not figured out why I get this:



The IDLE interface is very useful as mentioned here. You get a lot of help.





No comments:

Post a Comment

Do you know what you installed while custom installing SQL Server 2022?

 When you install any software in Windows OS, the key information gets into the Registry and some of which you can look up in the control pa...