Chinaunix首页 | 论坛 | 博客
  • 博客访问: 9396464
  • 博文数量: 1747
  • 博客积分: 12961
  • 博客等级: 上将
  • 技术积分: 20060
  • 用 户 组: 普通用户
  • 注册时间: 2009-01-09 11:25
个人简介

偷得浮生半桶水(半日闲), 好记性不如抄下来(烂笔头). 信息爆炸的时代, 学习是一项持续的工作.

文章分类

全部博文(1747)

文章存档

2024年(23)

2023年(26)

2022年(112)

2021年(217)

2020年(157)

2019年(192)

2018年(81)

2017年(78)

2016年(70)

2015年(52)

2014年(40)

2013年(51)

2012年(85)

2011年(45)

2010年(231)

2009年(287)

分类: Windows平台

2018-01-12 11:39:18

基于 sqlite 、 mysql的连接示例

python3 有自带的 sqlite3 模块以及 Sqlite3 数据库, 可以直接进行数据库程序设计。
对象连接方法
db.close()
db.commit()
db.cursor()
db.rollback()

游标对象的属性和方法
c --> cursor
c.arraysize  : fetchmany()返回的行数
c.close(): 游标超出范围外时自动执行此操作
c.description: 一个7元组, 描述了每个相继的游标c组成的列。
c.execute(sql,params)执行查询
c.executemany(sql, seq_of_params) seq_of_params为序列或者映射, 对其每一项执行sql (不适合select)
c.fetchall()  返回序列, 包括所有未取回的行
c.fetchmany(size)  返回一个行序列(每个行也是一个序列), size 默认 = c.arraysize
c.fetchone(): 返回结果集的下一行, 或者 None, 没有结果集则为 异常。
c.rowcount: 最近一次操作影响的行数。



点击(此处)折叠或打开

  1. db = sqlite3.connect(filename)返回数据库对象病打开。
  2. mycursor = db.cursor() 数据库操作通过游标完成

  3. mycursor.execute("create table A ("
  4.     "id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL,"
  5.     "name TEXT UNIQUE NOT NULL,"
  6.     "PID INTEGER NOT NULL,"
  7.     "FOREIGN KEY(PID) REFERENCES table_B)"
  8. )

  9. db.commit()

  10. mycursor.execute("insert into A(name,PID)"
  11.     "values(?,?,?)", ("ray",386396)) 使用 ? 占位符, 后面必须为元组,注意一元组格式 (1,
  12. db.commit()
  13.  
  14. mycursor.execute("select * from A where name=?", ("ray",))
  15. fields = mycursor.fetchone()
  16. print(fields[0] if fields is not None else None)
  17.  
  18. 或者用
  19. mycursor.execute("select id,name,pid from A where name=:name", dict(name="ray",))
  20. cid,cname,cpid = mycursor.fetchone()

  21. db.close()

对于复杂一点的mysql, 附上以前的一个代码

点击(此处)折叠或打开

  1. # coding=UTF-8

  2. import cv2
  3. import numpy as np
  4. from feature_get import FaceVgg
  5. from similarity import cosine_similarity
  6. import sys
  7. from imp import reload
  8. from struct import pack, unpack
  9. from main import get_run_flags, set_run_flags
  10. from queue import Queue
  11. import time
  12. import datetime
  13. import threading
  14. import udp_server

  15. '''
  16. map class to table of mysql
  17. '''

  18. from sqlalchemy import create_engine
  19. from sqlalchemy import Column, String, Integer, BLOB
  20. from sqlalchemy.orm import sessionmaker
  21. from sqlalchemy.ext.declarative import declarative_base


  22. engine = create_engine("mysql+pymysql://ray:hattie@localhost:3306/db_faces", max_overflow=5)
  23. Base = declarative_base()
  24. DBSession = sessionmaker(bind=engine)
  25. session = DBSession()

  26. class FaceItem(Base):
  27.     __tablename__ = 'tblFaces'
  28.     fPersonID = Column(Integer, primary_key=True, autoincrement=True)
  29.     fGroup = Column(Integer, nullable=False)
  30.     fPersonName = Column(String(32), nullable=False)
  31.     bFeature = Column(BLOB, nullable=False)
  32.     bImage = Column(BLOB, nullable=False)

  33. queue_face_request_item = Queue(10)
  34. def new_face_request_item(client_addr, requst_type, img, group, names, fSeq):
  35.     global queue_face_request_item
  36.     item = [client_addr, requst_type, img, group, names, fSeq]
  37.     #queue_face_request_item.put(item)
  38.     queue_face_request_item.put_nowait(item)
  39.     

  40. def face_feature_exec(params):
  41.     global queue_face_request_item
  42.     print (params)
  43.     face_vgg_net = FaceVgg() # load caffe engine
  44.     faceset = session.query(FaceItem).all() #load current dataset
  45.     
  46.     while not get_run_flags(): #not bTerminated:
  47.         # get image from list, proc it , then send message back.
  48.         try:
  49.             item = queue_face_request_item.get()
  50. #-------------------------------------------------------------------------------------------------------------------------
  51.             if item[1] == udp_server.CMD_FACE_REQ:
  52.                 print("Face Recognize.")
  53.                 extract_start = datetime.datetime.now().microsecond
  54.                 feat_blob = face_vgg_net.extract_face_feat(item[2])
  55.                 extract_end = datetime.datetime.now().microsecond
  56.                 print(["### extract", extract_start - extract_end])
  57.                 
  58.                 max_score = 0.0
  59.                 row_idx = faceset[0]
  60.                 for row in faceset:
  61.                     feat_list = []
  62.                     fFeat = row.bFeature
  63.                     i = 0
  64.                     while i<4096 :
  65.                         tmp = fFeat[i*4:i*4+4]
  66.                         f_val = unpack('f', tmp)[0]
  67.                         feat_list.append(f_val)
  68.                         i = i+1
  69.                         
  70.                     feat_db = np.array(feat_list)
  71.                     extract_start = datetime.datetime.now().microsecond
  72.                     similarity = cosine_similarity(feat_blob, feat_db)
  73.                     extract_end = datetime.datetime.now().microsecond
  74.                     if similarity>max_score:
  75.                         print(["### compare", extract_start-extract_end])
  76.                         max_score = similarity
  77.                         row_idx = row
  78.                         
  79.                 if max_score > 0.60:
  80.                     print( "best score is %f" % max_score )
  81.                     udp_server.sendback_recognized_ok(item[0], item[5], row_idx.fGroup, row_idx.fPersonID, row_idx.fPersonName, max_score)
  82.                     
  83.                 
  84. #-------------------------------------------------------------------------------------------------------------------------
  85.             elif item[1] == udp_server.CMD_REGISTER:
  86.                 print("Face Register.")
  87.                 feat_blob = face_vgg_net.extract_face_feat(item[2])
  88.                 
  89.                 img_encode = cv2.imencode('.jpg', item[2])[1]
  90.                 data_img_encode = np.array(img_encode)
  91.                 img_blob = data_img_encode.tostring()
  92.                 
  93.                 row_item = FaceItem(fGroup=item[3], fPersonName=item[4], bFeature=feat_blob, bImage=img_blob)
  94.                 session.add(row_item)
  95.                 session.commit()
  96.                 #print(row_item.fPersonID)
  97.                 
  98.                 faceset = session.query(FaceItem).all() #load current dataset
  99.                 #print(len(faceset))
  100.                 
  101.                 #send OK to client. 0->clientaddr, 5->fseq
  102.                 udp_server.sendback_regist_ok(item[0], item[5])
  103.                 
  104.                 print("OK")
  105.                 
  106.         except:
  107.             sleep(0.01)
  108.         
  109.     
  110.     set_run_flags(False)
  111.     
  112. # --------------------------------------------------------------------------------------------------
  113. def main_thread():
  114.     threads = [] # list
  115.     thr_face_server = threading.Thread(target=face_feature_exec, args=(u'FaceReco 服务监听',))
  116.     threads.append(thr_face_server)
  117.     
  118.     for t in threads:
  119.         t.setDaemon(True)
  120.         t.start()
  121.         
  122.     for t in threads:
  123.         t.join()
  124.     
  125.     print("Thread Face is Over.\n")

  126. '''
  127.    循环遍历列表
  128. '''
  129. def main_1():
  130.     faceset = session.query(FaceItem).all()
  131.     
  132.     fFeat = faceset[0].bFeature
  133.     #每四個字節爲一个float类型
  134.     print(fFeat)
  135.     print(len(fFeat))
  136.     i = 0
  137.     feat_list = []
  138.     while i<4096 :
  139.         tmp = fFeat[i*4:i*4+4]
  140.         f_val = unpack('f', tmp)[0]
  141.         feat_list.append(f_val)
  142.         i = i+1
  143.         
  144.     feat_1 = np.array(feat_list)
  145.     print(feat_1)
  146.     print(type(feat_1))

  147.     fImage = faceset[0].bImage
  148.     img_encode = np.fromstring(fImage, np.uint8)
  149.     img_decode = cv2.imdecode(img_encode, 1)
  150.     cv2.imshow('face', img_decode)
  151.     cv2.waitKey()
  152.     
  153. '''
  154.    add one record.
  155. '''
  156. def main_2():
  157.     face_vgg_net = FaceVgg()
  158.     
  159.     img_1 = cv2.imread('img/0_2.jpg')
  160.     feat_1 = face_vgg_net.extract_face_feat(img_1)
  161.     print(feat_1)
  162.     print(type(feat_1))
  163.     

  164.     img_encode = cv2.imencode('.jpg', img_1)[1]
  165.     data_img_encode = np.array(img_encode)
  166.     str_img = data_img_encode.tostring()
  167.         
  168.     session.query(FaceItem).delete()
  169.     session.commit()
  170.     
  171.     item = FaceItem(fGroup=0, fPersonName='0_2', bFeature=feat_1, bImage=str_img)
  172.     session.add(item)
  173.     session.commit()
  174.     print("OK")


  175. if __name__ == '__main__':
  176.     reload(sys)
  177.     #main_2()
  178.     #main_1()
  179.     main_thread()























阅读(1963) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~