zoukankan      html  css  js  c++  java
  • python SQLServer 存储图片

    需求是需要用python往 SqlServer中的image类型字段中插入二进制图片

    核心代码,研究好几个小时的代码:

     安装pywin32,adodbapi

    安装pywin32,adodbapi
    
    image_url = "图片链接"
    try:
        image_result = session.get(url=image_url, headers=headers, stream=True)
    except:
        image_result = session.get(url=image_url, headers=headers, stream=True)
    
    local_filename = md5(image_url) + ".png"
    print "图片下载成功"
    
    with open(local_filename, 'wb') as f:
        for chunk in image_result.iter_content(chunk_size=1024):
            if chunk:  # filter out keep-alive new chunks
                f.write(chunk)
                f.flush()
        f.close()
    
    # 读取图片,二进制格式,注意是rb
    f1 = open(local_filename, "rb", )
    b = f1.read()
    f1.close()
    
    # adodbapi支持插入二进制数据流
    Cfg = {'server': 'XXXXXXX9', 'password': 'XXXXXXX', 'db': 'XXXXXXX'}
    constr = "Provider=SQLOLEDB.1; Initial Catalog=%s; Data Source=%s; user ID=%s; Password=%s; " % (Cfg['db'], Cfg['server'], 'drc_sql', Cfg['password'])
    conn = adodbapi.connect(constr)
    cursor = conn.cursor()
    print "DocId", DocId
    # docimageid在数据表是主键
    
    docimageid = str(DocId) + str(image_location)
    print "docimageid", docimageid
    
    sql6 = " INSERT INTO docImages (DocId,docimageid,purpose) VALUES (%s,'%s','%s') " % (int(DocId), int(docimageid), 'doclogo')
    # print sql6
    cursor.execute(sql6)
    conn.commit()
    
    #插入图片
    cursor.execute('update docImages set Img=? where docimageid= ? ',(adodbapi.Binary(b), docimageid,))
    conn.commit()
    print "图片保存成功"
    
    先插入相关信息,再去update图片到数据库里面。
  • 相关阅读:
    hdu 4496 D-City 并查集
    hdu 4493 Tutor 水题
    codeforces 377A. Puzzles 水题
    hdu 1257 小希的迷宫 并查集
    图论500题
    cdoj 93 King's Sanctuary 傻逼几何题
    cdoj 题目简单分类
    cdoj 80 Cube 水题
    cdoj 71 I am Lord Voldemort 水题
    cdoj 65 CD Making 水题
  • 原文地址:https://www.cnblogs.com/xuchunlin/p/12850189.html
Copyright © 2011-2022 走看看