专栏名称: 生信杂谈
生物信息学;生物信息;计算机辅助药物设计;测序分析;Python;R;机器学习;论文写作;网站制作;LOL;dota2。
目录
相关文章推荐
51好读  ›  专栏  ›  生信杂谈

#Pyhton# 使用Peewee玩转SQL数据库--导入数据

生信杂谈  · 公众号  ·  · 2017-06-29 14:54

正文

请到「今天看啥」查看全文


peewee import Model, CharField, ForeignKeyField
class Category (Model) : name = CharField()    parent = ForeignKeyField( 'self' ,
related_name= 'children' ,
null= True )

每个Filed都有一些参数可以设置:

  • null = False,当前这个Field是否可以为null值

  • unique = False, 当前这个Field中的值是否唯一,比如id

  • default = None,指定一个默认值

更多

关于Sqlite多说几句(其他数据库可不可以这样用,不清楚,没试过)

一下是关于commit的问题,默认Sqlite是自动commit的,问题就是巨慢,因此连接数据库时可以指定autocommit为False,但是就需要用一下三种方式手动进行commit,后边还有一个atomic()功能与transaction()一致

# Define a database with autocommit turned off.
db = SqliteDatabase('my_app.db', autocommit=False)

# You must call begin()
db.begin() User.create(username='charlie') db.commit()

# If using a transaction, then no changes are necessary.

with db.transaction():    User.create(username='huey')

# If using a function decorated by transaction,
# no changes are necessary.
@db.transaction()
def create_user(username):    User.create(username=username)

言归正传,开始举例

基本使用方法

我使用Sqlite数据库来做展示,Sqlite可以直接导入导出CSV文件,官方也给出了解决方法 【详情】
然而,我还是决定自己处理,毕竟有很多数据需要修饰什么的
第一次接触这个模块是从《Python高效开发实战Django Tornado Flask Twisted》(刘长龙著),对它的第一印象就是貌似很简单(?),因此,就直接沿着这个模块用下来了。
以Human protein atlas下载到的细胞系表达量数据为例,简单说明一些用法

下载到一个CSV文件,总大小51.3M

一共包含五列数据,分别是ensembl_id,gene_name, tissue, value,value_type

1. 连接数据库

第一步,先指定一个数据库,新建各种所需的model

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
from peewee import Model
from peewee import SqliteDatabase
from peewee import CharField, FloatField

# autocommint顾名思义
# 就是每进行一个操作数据库是否自己commit一次,默认True
# 如果要进行大量的insert或者update操作的话,特别耗时,
# 不过不要紧,peewee提供了解决方法

db = SqliteDatabase(os.path.join(                    os.path.dirname(__file__),
                   'expression_value.db'),
                                         autocommit=True)
# 一个基础Model,没别的作用
# 如果一个数据库中有多个不同的表,
# 其中很多内容有一样,就可以通过基础类全部指定好






请到「今天看啥」查看全文