import sqlite3

con = sqlite3.connect('./db/user.db')
cur = con.cursor()

sql = 'create table if not exists user(id integer primary key, name text, age integer)'
cur.execute(sql)


# 插入一条 or 多条
def create_user():
    # insert
    # cur.execute('insert into user values(?,?,?)', (1, 'adleytales', 3))

    # insert manay
    list = [
        (2, 'para', 13),
        (3, 'aliya', 16),
        (4, 'balan', 12),
        (5, 'okok', 10),
    ]
    cur.executemany('insert into user values(?,?,?)', list)


# 查询
def select_users():
    cur.execute('select * from user')
    result = cur.fetchall()
    # [(1, 'adleytales', 3), (2, 'para', 13), (3, 'aliya', 16), (4, 'balan', 12), (5, 'okok', 10)]
    print(result)


def select_users2():
    cur.execute('select * from user')
    result = cur.fetchone()
    print(result) # (1, 'adleytales', 3)


def select_users3():
    cur.execute('select * from user')
    result = cur.fetchmany(2)
    print(result) # [(1, 'adleytales', 3), (2, 'para', 13)]


# 更新
def update_user():
    cur.execute('update user set name=? where id =?', ('new_adleytales', 5))


# 删除
def delete_user():
    cur.execute('delete from user where id=?', (3,))


# create_user()
# select_users()
# select_users2()
select_users3()
# update_user()
# delete_user()


con.commit()
con.close()

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐