zoukankan      html  css  js  c++  java
  • 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()
  • 相关阅读:
    C++ String详解
    乏力的编码很累,这里有私货..
    给自己~~微语&&歌单
    2019CSP-J第二轮 B题C题
    HDU 3966 树链剖分+树状数组 模板
    HDU 2255 KM算法 二分图最大权值匹配
    HDU 4280 ISAP+BFS 最大流 模板
    HDU 6181 第k短路
    假装会python--爬取贴吧正文
    HDU 6170 dp
  • 原文地址:https://www.cnblogs.com/lizhaoyao/p/13717381.html
Copyright © 2011-2022 走看看