栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在python中将SQL表返回为JSON

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在python中将SQL表返回为JSON

就个人而言,我更喜欢使用SQLObject进行此类操作。我改编了一些必须快速完成的测试代码:

import simplejsonfrom sqlobject import *# Replace this with the URI for your actual databaseconnection = connectionForURI('sqlite:/:memory:')sqlhub.processConnection = connection# This defines the columns for your database table. See SQLObject docs for how it# does its conversions for class attributes <-> database columns (underscores to camel# case, generally)class Song(SQLObject):    name = StringCol()    artist = StringCol()    album = StringCol()# Create fake data for demo - this is not needed for the real thingdef MakeFakeDB():    Song.createTable()    s1 = Song(name="B Song",   artist="Artist1",   album="Album1")    s2 = Song(name="A Song",   artist="Artist2",   album="Album2")def Main():    # This is an iterable, not a list    all_songs = Song.select().orderBy(Song.q.name)    songs_as_dict = []    for song in all_songs:        song_as_dict = { 'name' : song.name, 'artist' : song.artist, 'album' : song.album}        songs_as_dict.append(song_as_dict)    print simplejson.dumps(songs_as_dict)if __name__ == "__main__":    MakeFakeDB()    Main()


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/449184.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号