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源码分享

神经网络python源码分享

神经网络的逻辑应该都是熟知的了,在这里想说明一下交叉验证 交叉验证方法: 看图大概就能理解了,大致就是先将数据集分成K份,对这K份中每一份都取不一样的比例数据进行训练和测试。得出K个误...

pycharm远程linux开发和调试代码的方法

pycharm远程linux开发和调试代码的方法

pycharm是一个非常强大的python开发工具,现在很多代码最终在线上跑的环境都是linux,而开发环境可能还是windows下开发,这就需要经常在linux上进行调试,或者在lin...

pandas计数 value_counts()的使用

pandas计数 value_counts()的使用

在pandas里面常用value_counts确认数据出现的频率。 1. Series 情况下: pandas 的 value_counts() 函数可以对Series里面的每个值进行计...

安装python时MySQLdb报错的问题描述及解决方法

问题描述: windows安装python mysqldb时报错python version 2.7 required,which was not found in the regist...

python matplotlib中的subplot函数使用详解

python matplotlib中的subplot函数使用详解

python里面的matplotlib.pylot是大家比较常用的,功能也还不错的一个包。基本框架比较简单,但是做一个功能完善且比较好看整洁的图,免不了要网上查找一些函数。于是,为了节省...