Python3实现连接SQLite数据库的方法

yipeiwu_com5年前Python基础

本文实例讲述了Python3实现连接SQLite数据库的方法,对于Python的学习有不错的参考借鉴价值。分享给大家供大家参考之用。具体方法如下:

实例代码如下:

import sqlite3

db = r"D:\pyWork\test.db"  #pyWork目录下test.db数据库文件
drp_tb_sql = "drop table if exists staff"
crt_tb_sql = """
create table if not exists staff(
  id integer primary key autoincrement unique not null,
  name varchar(100),
  city varchar(100)
);
"""

#连接数据库
con = sqlite3.connect(db)
cur = con.cursor()

#创建表staff
cur.execute(drp_tb_sql)
cur.execute(crt_tb_sql)

#插入记录
insert_sql = "insert into staff (name,city) values (?,?)"  #?为占位符
cur.execute(insert_sql,('Tom','New York'))
cur.execute(insert_sql,('Frank','Los Angeles'))
cur.execute(insert_sql,('Kate','Chicago'))
cur.execute(insert_sql,('Thomas','Houston'))
cur.execute(insert_sql,('Sam','Philadelphia'))

con.commit()

#查询记录
select_sql = "select * from staff"
cur.execute(select_sql)

#返回一个list,list中的对象类型为tuple(元组)
date_set = cur.fetchall()
for row in date_set:
  print(row)

cur.close()
con.close()

希望本文实例对大家的Python学习有所帮助。

相关文章

python将xml xsl文件生成html文件存储示例讲解

前提:安装libxml2 libxstl 官方网站:http://xmlsoft.org/XSLT/index.html 安装包下载:http://xmlsoft.org/sources...

详解windows python3.7安装numpy问题的解决方法

详解windows python3.7安装numpy问题的解决方法

我的是win7的系统,去python官网下载python3.7安装 CMD  #打开命令窗口 pip install numpy #在cmd中输入 提示 需要c++14....

对Django项目中的ORM映射与模糊查询的使用详解

ORM映射 什么是ORM映射?在笔者认为就是对SQL语句的封装,所写语句与SQL对应语句含义相同,使开发更加简单方便,不过也是存在弊端的,使程序运行效率下降。例如: UserInf...

用Python中的wxPython实现最基本的浏览器功能

通常,大多数应用程序通过保持 HTML 简单来解决大多数浏览器问题 ― 或者说,根据最低共同特性来编写。然而,即便如此,也仍然存在字体和布局的问题,发行新浏览器和升级现有浏览器时,也免不...

python单链表实现代码实例

链表的定义:链表(linked list)是由一组被称为结点的数据元素组成的数据结构,每个结点都包含结点本身的信息和指向下一个结点的地址。由于每个结点都包含了可以链接起来的地址信息,所以...