Sqlite3数据库Python基础操做

1.数据库操做步骤

使用sqlite3须要导入包sqlite3,数据库在操做时须要先链接数据库,而后建立游标Cursor。sql

当程序运行完之后,须要先关闭游标,而后再关闭数据库。数据库

(1)查询操做

查询操做的步骤为:1.使用SQL语句进行查询,2.从fetchall中将查询结果读出函数

使用Cursor对象执行select语句时,经过featchall()能够拿到结果集。结果集是一个list,每一个元素都是一个tuple,对应一行记录。fetch

示例代码以下spa

import sqlite3#导入包
conn=sqlite3.connect('sample_database')#链接到SQLite数据库
cursor=conn.cursor()#建立一个Cursor
cursor.execute("select employee.firstname,employee.lastname from employee")#使用SQL语句对数据库进行操做
for row in cursor.fetchall():#从fetchall中读取操做
    print(row)
cursor.close()#关闭Cursor
conn.close()#关闭数据库

(2)插入、删除与更新操做

步骤为:1.使用SQL语句进行查询,2.提交操做code

import sqlite3
conn=sqlite3.connect('sample_database')#链接到SQLite数据库
cursor=conn.cursor()#建立一个Cursor
cursor.execute('create table user (id varchar(20) primary key, name varchar(20))')#用SQL语句建立一个表
cursor.execute('insert into user (id, name) values (\'1\', \'Michael\')')#用SQL语句向表中插入数据
print(cursor.rowcount)#显示插入的函数
cursor.close()#关闭Cursor
conn.commit()#提交操做
conn.close()#关闭数据库

使用Cursor对象执行insertupdatedelete语句时,执行结果由rowcount返回影响的行数,就能够拿到执行结果sqlite

参考资料

使用SQLite-廖雪峰:https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001388320596292f925f46d56ef4c80a1c9d8e47e2d5711000对象

相关文章
相关标签/搜索