python操作sqlite的小例子

照着菜鸟教程 学习python操作sqlite

ubuntu 安装 

 sudo apte-get install sqlite3 

找到了 

sqlite3/bionic-updates,bionic-security,now 3.22.0-1ubuntu0.4 amd64 [installed]
Command line interface for SQLite 3

然后安装 sqlitebrowser

 sudo apt search sqlitebrowser 

找到这个

sqlitebrowser/bionic,now 3.10.1-1.1 amd64 [installed]
GUI editor for SQLite databases

之后就是python 脚本了

获取结果集按字典索引获取 我找了找资料 才处理好 row['NAME'] 不然就得用索引数组了

定义 dict_factory 来替换 conn.row_factory

#!/usr/bin/python

import sqlite3
def dict_factory(cursor, row): 
  d = {} 
  for idx, col in enumerate(cursor.description): 
    d[col[0]] = row[idx] 
  return d 

conn = sqlite3.connect('test.db')
conn.row_factory = dict_factory
print "Opened database successfully"
c = conn.cursor()
c.execute('''CREATE TABLE if not exists COMPANY
       (ID INTEGER PRIMARY KEY AUTOINCREMENT    NOT NULL,
       NAME           TEXT    NOT NULL,
       AGE            INT     NOT NULL,
       ADDRESS        CHAR(50),
       SALARY         REAL);''')
print "Table created successfully"

c.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
      VALUES (NULL, 'Paul', 32, 'California', 20000.00 )")

c.execute("UPDATE COMPANY SET NAME='Mark_update' WHERE ID = 4")

cursor = conn.execute("DELETE from COMPANY WHERE ID = 4")

conn.commit()
print "Records created successfully"


cursor = c.execute("SELECT name,age,address from COMPANY")
for row in cursor.fetchall():
  print row['NAME']

conn.close()

 

posted @ 2020-09-23 12:01  李照耀  阅读(532)  评论(0编辑  收藏  举报