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

yipeiwu_com6年前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学习有所帮助。

相关文章

Django的数据模型访问多对多键值的方法

这里先来借用一个书本(book)的数据模型作为例子: from django.db import models class Publisher(models.Model): n...

Python获取当前路径实现代码

 Python获取当前路径实现代码 import os,sys 使用sys.path[0]、sys.argv[0]、os.getcwd()、os.path.abspath(__...

pytorch GAN伪造手写体mnist数据集方式

pytorch GAN伪造手写体mnist数据集方式

一,mnist数据集 形如上图的数字手写体就是mnist数据集。 二,GAN原理(生成对抗网络) GAN网络一共由两部分组成:一个是伪造器(Generator,简称G),一个是判别器(...

机器学习python实战之决策树

机器学习python实战之决策树

决策树原理:从数据集中找出决定性的特征对数据集进行迭代划分,直到某个分支下的数据都属于同一类型,或者已经遍历了所有划分数据集的特征,停止决策树算法。   每次划分数据集的特征都有很多,那...

Python切片用法实例教程

本文以实例形式讲述了Python中切片操作的用法,分享给大家供大家参考借鉴,具体如下: 取一个list或tuple的部分元素是非常常见的操作。比如,一个list如下: >>...