python操作sqlite

2019-08-17  本文已影响0人  次序
import csv
# 导入sqlite3模块
import sqlite3

from django.http import HttpResponse


def index(request):
    # 创建链接对象
    # 打开一个到 SQLite 数据库文件 db.mysite 的链接
    # 如果该数据库不存在则会自动创建,可以指定带有文件路径的文件名
    conn = sqlite3.connect("db.mysite")

    # 获取游标对象用来操作数据库
    cursor = conn.cursor()

    # 创建表
    # 插入user表
    # id int型 主键自增
    # name varchar型 最大长度20 不能为空
    cursor.execute(
        '''create table if not exists user(id integer primary key autoincrement,name varchar(20) not null)''')


    # 插入记录
    # 插入一条id=1 name='xiaoqiang'的记录
    # cursor.execute('''insert into user(name) values('xiaoqiang2')''')
    # cursor.execute('''insert into user(name) values('tangbofu2')''')

    # 修改记
    # 修改id=1记录中的name为xiaoming
    # cursor.execute('''update user set name='xiaoming' where id=1''')

    # 删除记录
    # 删除id=1的记录
    # cursor.execute('''delete from user where id=1''')

    # 查找记录
    # 查找user表中id=1的记录
    # cursor.execute('''select * from user where id=2''')
    cursor.execute('''select * from user''')
    # 获得结果
    values = cursor.fetchall()

    # 前面的修改只是将数据缓存在内存中并没有正真的写入数据库,需要提交事务才能将数据写入数据库
    # 操作完后要确保打开的Connection对象和Cursor对象都正确地被关闭,否则,资源就会泄露。

    # 提交事务
    conn.commit()
    # 关闭链接
    conn.close()

    return HttpResponse(values)

#生成csv文件
def some_view(request):
    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'

    writer = csv.writer(response)
    writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
    writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])

    return response

上一篇 下一篇

猜你喜欢

热点阅读