python3-操作SQLite、创建表、添加数据、查询数据

SQLlte数据类型

这里写图片描述

SQLite能保存什么样的数据类型 ??   可以保存空值、整数、浮点数、字符串和blob。

什么是blob ?? 是二进制大对象。例如图片、音乐、zip文件。

什么是游标 ??   游标是在数据库中用来移动和执行查询的对象。

SQL的全部知识呢??? 远不止这些网站 http://www.runoob.com/sql/sql-tutorial.html 有一个很好的初学教程

创建数据库,创建表

如果要使用SQL必须要导入sqlite3库。
这里写图片描述

import sqlite3

# '''创建一个数据库,文件名'''
conn = sqlite3.connect('./mytest1.db')
# '''创建游标'''
cursor = conn.cursor()

# '''执行语句'''

sql = '''create table students (
        name text,
        username text,
        id int)'''

cursor.execute(sql)

# '''使用游标关闭数据库的链接'''
cursor.close()

添加数据

要添加一些数据到表中,需要使用insert命令和一些特殊的格式。
这里写图片描述

import sqlite3


conn = sqlite3.connect('mytest.db')
cursor = conn.cursor()

print('hello SQL')

while True:
    name  = input('student\'s name')
    username = input('student\'s username')
    id_num = input('student\'s id number:')
 # '''insert语句 把一个新的行插入到表中'''

    sql = ''' insert into students
              (name, username, id)
              values
              (:st_name, :st_username, :id_num)'''
    # 把数据保存到name username和 id_num中
    cursor.execute(sql,{'st_name':name, 'st_username':username, 'id_num':id_num})
    conn.commit()
    cont = ('Another student? ')
    if cont[0].lower() == 'n':
        break
cursor.close()

这里写图片描述


查询数据

这里写图片描述

(*) 告诉数据库给出所有内容。


这里写图片描述


code:

import sqlite3
import os
os.chdir('d:\\pycharm\\lesson\\sn01')

# conn = sqlite3.connect('D:\\pycharm\\lesson\\sn01\\SQL\\mytest.db')
conn = sqlite3.connect(r'./SQL/mytest.db')
cursor = conn.cursor()

# 查询所有的学生表
# sql = '''select * from students'''

''' 得到数据库中的名字'''
sql = "select rowid,  username from students"

# 执行语句
results = cursor.execute(sql)

# 遍历打印输出
all_students = results.fetchall()
for student in all_students:
    print(student)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值