【Python web 开发】 bottle 简单教程 (四)

本文详细介绍如何使用Python操作SQLite数据库,包括数据库的创建、表的创建与删除、数据的增删改查等基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本来打算做一个简单的CRUD操作

但是发现Python对DB的操作还没有介绍,你懂的。

Python可以操作多种数据库,

仅针对sqlite做简单的操作,其他类同


一:下载sqlite,安装

http://www.sqlite.org/download.html

sqlite-shell-win32-x86-3071100.zip
(253.56 KiB)

下载它,然后解压缩,恭喜你,

sqlite搞定了。


解压缩后文件夹下只有一个文件sqlite3.exe,CMD下,cd到这个目录,执行sqlite3.exe test.db

恭喜你,数据库创建成功了。

你可以在cmd中各种命令搞定sqlite,嘿嘿,下面看看python怎么搞定它。


二:python搞定它

官方doc

http://docs.python.org/py3k/library/sqlite3.html


那么,要是使用sqlite3模块了,


To use the module, you must first create a Connection object that represents the database.

用这个模块,你必须首先建立一个链接来表示db


import sqlite3

You can also supply the special name :memory: to create a database in RAM.

你也可以把数据库建立在内存中,

官方doc写的很好,强烈推荐看看,所以下面的例子,都是很简单的,LZ发现实在没法比官方doc写更好,忍了,本来还想直接上官方doc的,但是发现不行。

官方doc是e文,本想翻一下,但是发现几乎不需要翻译,就能看懂。囧!!!


建表,删表,增加,查询写了,那么删除和更新还能不会搞吗?生气

import sqlite3
#To use the module, you must first create a Connection object that represents the database. 


def createTable():
#    You can also supply the special name :memory: to create a database in RAM.
#    采用特殊名称:memory:可以建在内存中
    conn = sqlite3.connect('sqlite/example')
    print(conn,'建立成功')
    
    #cursor必须要有,否则,你啥也干不了
    c = conn.cursor()

    # 建表
    c.execute('create table test (id int, name text)')
    
    # 增加一行
    c.execute("insert into test values (1,'jack')")
    
    # 提交
    conn.commit()
    
    # 关闭
    c.close()
    conn.close()
    
#查询
def find():
    conn = sqlite3.connect('sqlite/example')
    c = conn.cursor()
    c.execute('select * from test')
    res = c.fetchall()
    for row in res:
        print(row)
    
    
def dropTable():
    conn = sqlite3.connect('sqlite/example')
    c = conn.cursor()
    c.execute('drop table test')
    conn.commit()
    c.close()
    conn.close()
    
#要使用绑定变量的方法,不要使用字符串拼接的方式
def findById(id):
    conn = sqlite3.connect('sqlite/example')
    c = conn.cursor()
    
    c.execute('select * from test where id = ? ',(id,))
    print(c.fetchall())
    
#插入    
def insert():
    conn = sqlite3.connect('sqlite/example')
    c = conn.cursor()
    c.execute("insert into test values (2,'tom')")
    conn.commit()
    c.close()
    conn.close()
    
#批量插入,使用变量绑定
def insertLarge():
    conn = sqlite3.connect('sqlite/example')
    c = conn.cursor()
    
    for r in [(3, 'lily'),(4, 'cati')]:
        c.execute("insert into test values (?,?)",r)
        
    conn.commit()
    c.close()
    conn.close()   
     
#dropTable()
#createTable()
#insert()
#findById(2)
#insertLarge()


find()









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值