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之pandas用法大全

一、生成数据表 1、首先导入pandas库,一般都会用到numpy库,所以我们先导入备用: import numpy as np import pandas as pd 2、导入C...

Python使用turtule画五角星的方法

本文实例讲述了Python使用turtule画五角星的方法。分享给大家供大家参考。具体实现方法如下: #!/usr/bin/env python import turtle impo...

python检测远程端口是否打开的方法

本文实例讲述了python判断远程端口是否打开的方法。分享给大家供大家参考。具体实现方法如下: import socket sk = socket.socket(socket.AF_...

Python3之字节串bytes与字节数组bytearray的使用详解

字节串bytes 字节串也叫字节序列,是不可变的序列,存储以字节为单位的数据 字节串表示方法: b"ABCD" b"\x41\x42" ... 字节串的构造函数: bytes()...

python ddt数据驱动最简实例代码

在接口自动化测试中,往往一个接口的用例需要考虑 正确的、错误的、异常的、边界值等诸多情况,然后你需要写很多个同样代码,参数不同的用例。如果测试接口很多,不但需要写大量的代码,测试数据和代...