python - python database connectivity with sqlite3

Python has in-built a database engine that is the sqlite3 which does not require a server and a client, unlike mysql and others. sqlite3 uses a file as the store, also you can use ":memory:" to use memory as the storage. Let's see the code below on how we can make use the the sqlite engine.


import sqlite3
conn = sqlite3.connect("datafile")

cursor = conn.cursor()
print(cursor)

cursor.execute("create table test (name text, count integer)") # create table
cursor.execute("insert into test (name, count) values ('Bob', 1)") # insert values 
cursor.execute("insert into test (name, count) values (?, ?)", ('Jill', 15)) #insert values 

cursor.execute("insert into test (name, count) values (:username, :usercount)", {"username": "Joe", "usercount": 10}) #insert values, with variable name prefixed with : in the query and pass in a corresponding dictionary

result = cursor.execute("select * from test")
print(result.fetchall())

result = cursor.execute("select * from test where name like :name", {"name" : "bob"})
print(result.fetchall())

cursor.execute("update test set count = ? where name = ?", (20, "Jill"))
result = cursor.execute("select * from test")
print(result.fetchall())


result = cursor.execute("select * from test")
for row in result:
    print(row)

cursor.execute("update test set count=? where name=?", (20, "Jill"))
conn.commit()
conn.close()    

connection object will enable you to create connecton to a database. then you can use the cursor object which you can make queries against the database. you may retrieve the result from the execute method, and you can either do fetchall() to return the result collection or you can use the for loop to loop through the result set.

转载于:https://my.oschina.net/u/854138/blog/92090

你可能感兴趣的:(python - python database connectivity with sqlite3)