Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to browse an in memory sqlite database in python

I need to use an in memory sqlite database with the following constructor:

db = sqlite3.connect(':memory:')

But in debugging, I find it very inconvenient because unlike file-based database, I cannot browse the database in the debugger.

Is there a way to browse this database on the fly?

like image 323
atbug Avatar asked May 07 '26 08:05

atbug


1 Answers

You can write python scripts in debugger to perform any queries. For example, consider the following program:

import pdb
import sqlite3
con = sqlite3.connect(':memory:')
cur = con.cursor()
cur.execute('create table abc (id int, sal int)')
cur.execute('insert into abc values(1,1)')
cur.execute('select * from abc')
data = cur.fetchone()
print (data)
pdb.set_trace()
x = "y"

Once we enter debugging (pdb), we can write queries like the following:

D:\Sandbox\misc>python pyd.py
(1, 1)
> d:\sandbox\misc\pyd.py(11)<module>()
-> x = "y"
(Pdb) cur.execute('insert into abc values(2,2)')
<sqlite3.Cursor object at 0x02BB04E0>
(Pdb) cur.execute('insert into abc values(3,3)')
<sqlite3.Cursor object at 0x02BB04E0>
(Pdb) cur.execute('select * from abc')
<sqlite3.Cursor object at 0x02BB04E0>
(Pdb) rows = cur.fetchall()
(Pdb) for row in rows:    print (row)
(1, 1)
(2, 2)
(3, 3)
(Pdb)
like image 52
bprasanna Avatar answered May 09 '26 20:05

bprasanna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!