摘自以前CI实现的商城系统,做APP时需要实现数据接口,便用python实现了。
假设有表tp_article
| id | title | type |
| 1 | 哈哈 | 1 |
| 2 | 图样涂森坡 | 1 |
使用thinphp实现取出type为1的数据如下
M()->from(''tp_article'')->where('type=1')->select();
现通过python实现类似对mysql进行操作的封装
DB.select('*').fm('tp_article').where('type',1).all()
需要:django下的db模块
首先实现 mydb.py 文件,放于core目录下,实现模型类文件时需要import
from django.db import connection
cursor = connection.cursor()
'''
Simple function for one result sql
'''
#返回一条结果
def fetchone(sql):
cursor.execute(sql)
try:
col_names = [row[0] for row in cursor.description]
rs = dict(zip(col_names,cursor.fetchone()))
except:
rs = {}
return rs
<pre name="code" class="python">#返回多条结果def fetchall(sql): cursor.execute(sql) try: col_names = [row[0] for row in cursor.description] data = cursor.fetchall() rs = [dict(zip(col_names,raw)) for raw in data] except: rs=[] return rs
然后就是实现模型类文件db_mysql.py
from core.mydb import *
class Db_mysql(object):
'''build sql'''
sql=''
options={}
history=[]
def select(self,fields):
select

本文介绍了如何使用Python实现类似于ThinkPHP中针对Mysql操作的数据模型。通过一个例子展示了如何查询tp_article表中type为1的数据,利用Django的db模块,创建了一个DB类,并提供了select、from_和where等方法来简化数据库操作。
最低0.47元/天 解锁文章
811

被折叠的 条评论
为什么被折叠?



