I am back again to blog, dint got much of a time to really get going these days that was why the break. Any ways back to the topic and this time its Python. I am going to explain here just the basic thing u need to do for a database connectivity with some database like SQLite or Access or SQLyog..or whatever...the point is u would be able to access your data through ur program/script
This can be little tricky b'coz of a few reasons, Firstly b'coz that python does not have any kind of variable declaration and opening and closing braces which the normal c/c++ or other high end programmers find annoying..(well.. atleast i did).
Secondly b'coz if u are using sqlite and python then it uses transactions by default..
dint get it??? well lemme explain..
Before every
INSERT/UPDATE/DELETE/REPLACE
statement, Python’s sqlite3 implicitly opens a transaction. It automatically commits before a non-query statement, e.g. before a CREATE TABLE
statement or similar. This is kind of cool thing b'cos if an exception is thrown while you’re inserting data, the state of the database is not affected...BUT..when u open a db insert some values and close it...and then open it again and give a select query...u will get nothing and u can see the table is blank...
i played around a lot with this and finally i got to know about the python transaction thing...the solution is simple just commit the changes after each transaction.
so now..lets get our hands dirty with some python code
so the very first line..
python code starts with the very first line refering to the intrepreter of python nad would look like
#! c:/Python25/Python -for windows
#! user/bin/python-for linux
dbFile = "path of the db file"
#if your are using for a cgi file youmay need to import cgi library
import sqlite3
db = sqlite3.connect(dbFile)
c = db.cursor()
#creating table
c.execute('''create table stocks (date text, trans text, symbol text, qty real, price real)''')
#inserting a row of data
c.execute("""insert into stocks values ('2009-02-15','DPK','COOL',247,00.15)""")
#save (commit) the changes
db.commit()
c.close();
Yep..!!! Thats IT....the database is done and to view the datas you entered you can use the following code
>>>c = db.cursor()
>>>c.execute('select * from stocks')
>>>for row in c:
print row
( u'2009-02-15', u'DPK', u'COOL',247,00.15)
Well....thats all Folks!...see ya all in my next blog..Have fun!