【基础】学习笔记35-Python3 SQLite数据库-实操1

代码如下:

# sqlite3基本操作

# 在goods表中完成记录的插入、更新和删除

import sqlite3

items = [(6702, 'pencil', 90, 1.2),

        (3645, 'notebook', 56, 12.4),

        (5672, 'ruler', 22, 1.6)]

dbstr = 'C:\\sqlite3\\managedb.db'  # 数据库路径

con = sqlite3.connect(dbstr)  # 连接到数据库

cur = con.cursor()  # 创建游标对象

'''

cur.execute(

    "create table goods(id int primary key,name varchar(20),gnumber integer(2),price)"

)  # 创建表goods,表中包含id、name、gnumber、price四列'''

cur.execute(

    "insert or ignore into goods values(1003,'Pen',100,11)")  # 不存在,添加;存在,则不操作

cur.execute("insert or replace into goods values(?,?,?,?)",

            (2001, "mouse", 5, 22))  # 插入一行数。不存在,添加;存在,更新

cur.executemany("insert or ignore into goods values(?,?,?,?)", items)  # 插入多行

# 查询数据

cur.execute("select * from goods")

print(cur.fetchall())

id_list = []

# 遍历

for item in cur.execute("select * from goods"):

    print(item)

    id_list.append(item[0])

print(id_list)

con.commit()  # 事务提交

cur.close()

con.close()

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容