Python成为专业人士笔记–Sqlite3 模块

“专业人士笔记”系列目录:

创帆云:Python成为专业人士笔记--强烈建议收藏!每日持续更新!

Sqlite3 -一个不需要独立服务器进程的数据库

sqlite3模块是由Gerhard Haring编写的。要使用此模块,必须首先创建表示数据库的连接对象。这里的数据将存储在example.db文件中 :

import sqlite3
conn = sqlite3.connect('example.db')

一旦建立了连接,就可以创建一个游标对象并调用它的execute()方法来执行SQL命令

c = conn.cursor()
#建表
c.execute('''CREATE TABLE stocks
  (date text, trans text, symbol text, qty real, price real)''')

#插件一条数据
c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")

#运行commit命令提交
conn.commit()

#当完成命令执行后,我们要关闭连接 
#确保commit了所有操作,否则直接关闭连接可能会造成更改的操作丢失
conn.close()

从数据库获取值并进行错误处理

从SQLite3数据库获取值并打印select查询返回的行值

import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute("SELECT * from table_name where id=cust_id")
for row in c:
    print row # 将是一个列表

获取一条数据用 fetchone() 函数:

print c.fetchone()

同时获取多条数据用 fetchall() 函数:

a=c.fetchall() 
for row in a:
    print row

异常处理:

try:
    # SQL Code

except sqlite3.Error as e:
    print ("An error occurred:", e.args[0])

猜你喜欢

转载自blog.csdn.net/oSuiYing12/article/details/106379532
今日推荐