当前位置: 首页 > 工具软件 > fetion4j > 使用案例 >

Python模拟Web Fetion给好友发送信息(数据库编程模块)

楚岳
2023-12-01

数据库就主要说下sqlalchemy和elixir吧,其实我也没怎么学,就是之前在研究一个工程型代码的时候学习了点,然后就拿来直接用了。

先介绍下elixir:

官方的文档:http://elixir.ematia.de/trac/wiki/TutorialDivingIn

elixir主要就是用来封装sqlalchemy的ORM模块的(个人的见解)

代码:

数据库中的表有:FetionUsers, ProvincesMap,CitiesMap,sendInfo四个表

FetionUsers就是用来存用户信息的

ProvincesMap存省份名对应的字典,同理CitiesMap也是

sendInfo存你发送的信息

日志文件没有弄

'''
Created on 2012-3-16

@author: xkey
'''

from elixir import *

class FetionUsers(Entity):
    using_options(tablename = 'FetionUsers',autoload = True)
    provinceUser = ManyToOne('ProvincesMap')
    cityUser = ManyToOne('CitiesMap')

class ProvincesMap(Entity):
    using_options(tablename = 'ProvincesMap',autoload = True)
    fetionUser = OneToMany('FetionUsers')
    
class CitiesMap(Entity):
    using_options(tablename = 'CitiesMap',autoload = True)
    fetionUser = OneToMany('FetionUsers')

class SendMsg(Entity):
    using_options(tablename = 'sendInfo',autoload = True)

setup_all()

def ExecuteQuery(table,**kwargs):#查询一个表(table),**kwargs就是限制语句
    try:
        result = table.query.filter_by(kwargs).all()
        session.commit()
        return result
    except Exception,e:
        print e

def InsertRecords(table,**kwargs):#插入一条记录
    
    t = table(**kwargs)
    session.commit()
    session.close()
    return 1

def RemoveRecords(table,**kwargs):#删除一条记录
    try:
        t = table.query.filter_by(**kwargs).all()
        for item in t:
            session.delete(item)
    except Exception, e:
        print "No relation records"
        return 0
    session.commit()
    session.close()
    return 1


下面介绍sqlalchemy

它起到一个承上启下的作用,承上当然就是连接数据库,启下就是调用elixir去实现对数据库的各种操作

sqlalchemy学习网址有很多

推荐两个学习网址:

http://www.rmunn.com/sqlalchemy-tutorial/tutorial.html

http://mapfish.org/doc/tutorials/sqlalchemy.html


下面给出代码:代码简单易懂

#-*-coding:utf-8-*-

from elixir import *
import os,datetime,sys
from sqlalchemy.orm import sessionmaker


default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
    reload(sys)
    sys.setdefaultencoding(default_encoding)

class DbOper:
    def __init__(self,dbConString):
        self.__dbConString = dbConString
        if(self._setupDatabase() < 1):#连接数据库
            print "DataBase Initialize error"
    def insertPrivinceMap(self):
        provinceMap =\
        {
            "安徽":'AAH',"北京":'ABJ',"福建":'AFJ',"甘肃":'AGS',"广东":'AGD',\
            "广西":'AGX',"贵州":'AGZ',"海南":'AHI',"河北":'AHE',"河南":'AHA',\
            "黑龙江":'AHL',"湖南":'AHN',"湖北":'AHB',"吉林":'AJL','江苏':'AJS',\
            "江西":'AJX','辽宁':'ALN','内蒙':'AMN','宁夏':'ANX','青海':'AQH',\
            '山东':'ASD','山西':'ASX','陕西':'ASN','上海':'ASH','四川':'ASC',\
            '台湾':'ATW','天津':'ATJ','西藏':'AXZ','新疆':'AXJ','云南':'AYN',\
            '浙江':'AZJ','重庆':'ACQ','香港':'AXG','澳门':'AAM'
        }
        for key in provinceMap.keys():
            value = provinceMap[key]
            self.__db.InsertRecords(self.__db.ProvincesMap,realname = unicode(key),imagename = value)
        self.__db.session.commit()
        self.__db.session.close()
    
    def insertCityMap(self):
        cityMap = {'杭州':'hangzhou','滁州':'chuzhou','北京':'beijing'}
        for key in cityMap.keys():
            value = cityMap[key]
            self.__db.InsertRecords(self.__db.CitiesMap,realname = unicode(key),imagename = value)
        self.__db.session.commit()
        self.__db.session.close()
        
    def insertFetionUsers(self,user,province,city,id):
        self.__db.InsertRecords(self.__db.FetionUsers,username = unicode(user),province = unicode(province),\
                                    city = unicode(city),phoneid = id)
        self.__db.session.commit()
        self.__db.session.close()
        
    def insertSendMsgInfo(self,username,message,now = datetime.datetime.now()):
        self.__db.InsertRecords(self.__db.SendMsg,username = unicode(username),message = unicode(message),sendtime = now)
        self.__db.session.commit()
        self.__db.session.close()
    
    def querySendMsgInfo(self):
        res = self.__db.session.query(self.__db.SendMsg.id,self.__db.SendMsg.username,self.__db.SendMsg.message,\
                                      self.__db.SendMsg.sendtime).all()
        self.__db.session.commit()
        return res
    
    def queryFetionUsers(self):
        res = self.__db.session.query(self.__db.FetionUsers.username,self.__db.FetionUsers.province,\
                                      self.__db.FetionUsers.city,self.__db.FetionUsers.phoneid).all()
        self.__db.session.commit()
        return res
    def queryProvinceMap(self):
        res = self.__db.session.query(self.__db.ProvincesMap.realname,self.__db.ProvincesMap.imagename).all()
        self.__db.session.commit()
        return res
#        print len(res[0])
#        print res[0][0]
    
    def queryCityMap(self):
        res = self.__db.session.query(self.__db.CitiesMap.realname,self.__db.CitiesMap.imagename).all()
        self.__db.session.commit()
        return res
#        print res[0][0].encode('gbk')
    
    def deleteRecord(self,tableNum,name):
        if tableNum == 1:
            self.__db.RemoveRecords(self.__db.CitiesMap,realname = unicode(name))
        else :
            self.__db.RemoveRecords(self.__db.FetionUsers,username = unicode(name))
        self.__db.session.commit()
        self.__db.session.close()
    
    def deleteTable(self,tableNum):
        if tableNum == 1:
            self.__db.RemoveRecords(self.__db.CitiesMap)
        elif tableNum == 2:
            self.__db.RemoveRecords(self.__db.FetionUsers)
        self.__db.session.commit()
        self.__db.session.close()
    
    def _setupDatabase(self):
        try:
            from sqlalchemy.engine import create_engine
            
            engine = create_engine(self.__dbConString,echo = False)
            engine.text_factory = str
            metadata.bind = engine
            Session = sessionmaker(bind = engine,autocommit = True)
            import dborm
            self.__db = locals()['dborm'] #得到dborm.py中的方法,就是上面elixir的代码
        except Exception,e:
            print "Set up database error %s" % e
            return -1
        return 1
    def closeSession(self):
        self.__db.session.close()
        
    def insertCity(self,real,image):
        self.__db.InsertRecords(self.__db.CitiesMap,realname = unicode(real),imagename = image)
        self.__db.session.commit()
        self.__db.session.close()

一句SQL语句不用写就搞定了对数据库的各种操作,而且还屏蔽了各种数据库之间SQL语句语法的差异,这就是sqlchemy+elixir的强大之处

 类似资料: