zoukankan      html  css  js  c++  java
  • python数据库连接例子

    import sqlite3
    conn = sqlite3.connect('food.db')
    curs = conn.cursor()

    curs.execute('''
    CREATE TABLE IF NOT EXISTS food(
    id TEXT PRIMARY KEY,
    desc TEXT
    )
    ''')

    query = 'DELETE FROM food'
    print query
    curs.execute(query)

    query = 'INSERT INTO food VALUES(1, 2)'
    print query
    curs.execute(query) # sqlite3.IntegrityError: UNIQUE constraint failed: food.id

    sqlite3.OperationalError: no such column: A

    val = 'a'
    query = 'INSERT INTO food VALUES(2, ?)'
    print query
    curs.execute(query, val)

    vals = ['A', 'xyz']
    query = 'INSERT INTO food VALUES(?, ?)'
    print query
    curs.execute(query, vals)

    query = 'select * from food'
    print query
    curs.execute(query)
    names = [f[0] for f in curs.description]
    print names

    for row in curs.fetchall():
    for pair in zip(names, row):
    print '%s: %s' % pair
    print

    conn.commit()
    conn.close()

    food_query.py

    import sqlite3, sys
    
    conn = sqlite3.connect('food.db')
    curs = conn.cursor()
    
    # run as -> run configurations -> arguments id=1 do not blank!
    query = 'select * from food where %s' % sys.argv[1]
    print query
    curs.execute(query)
    names = [f[0] for f in curs.description]
    print names
    
    for row in curs.fetchall():
        for pair in zip(names, row):
            print '%s: %s' % pair
        print
    
    conn.commit()
    conn.close()
    
    

    参考:
    《python基础教程》

  • 相关阅读:
    AutoCompleteTextView控件的使用
    menu菜单
    fragment之间的通信
    fragment的生命周期
    用模型取代字典的好处
    使用fragment兼容低版本的写法
    模拟微信主界面
    动态替换fragment
    fragment入门
    Spring MVC学习总结(1)——Spring MVC单元测试
  • 原文地址:https://www.cnblogs.com/ouyida3/p/9751580.html
Copyright © 2011-2022 走看看