很多時候我們為了管理方便會把依稀很小的圖片存入數據庫,有人可能會想這樣會不會對數據庫造成很大的壓力,其實大家可以不用擔心,因為我說過了,是存儲一些很小的圖片,幾K的,沒有問題的!
再者,在這里我們是想講一種方法,python+ mysql存儲二進制流的方式
這里用的是Mysqldb,python里面最常用的數據庫模塊
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
import
MySQLdb
class
BlobDataTestor:
def
__init__ (
self
):
self
.conn
=
MySQLdb.connect(host
=
'localhost'
,user
=
'
',passwd='
',db='
0
')
def
__del__ (
self
):
try
:
self
.conn.close()
except
:
pass
def
closedb(
self
):
self
.conn.close()
def
setup(
self
):
cursor
=
self
.conn.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS `Dem_Picture` (
`ID` int(11) NOT NULL auto_increment,
`PicData` mediumblob,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;
"""
)
def
teardown(
self
):
cursor
=
self
.conn.cursor()
try
:
cursor.execute(
"Drop Table Dem_Picture"
)
except
:
pass
# self.conn.commit()
def
testRWBlobData(
self
):
# 讀取源圖片數據
f
=
open
(
"C:\\11.jpg"
,
"rb"
)
b
=
f.read()
f.close()
# 將圖片數據寫入表
cursor
=
self
.conn.cursor()
cursor.execute(
"INSERT INTO Dem_Picture (PicData) VALUES (%s)"
, (MySQLdb.Binary(b)))
# self.conn.commit()
# 讀取表內圖片數據,並寫入硬盤文件
cursor.execute(
"SELECT PicData FROM Dem_Picture ORDER BY ID DESC limit 1"
)
d
=
cursor.fetchone()[
0
]
cursor.close()
f
=
open
(
"C:\\22.jpg"
,
"wb"
)
f.write(d)
f.close()
# 下面一句的作用是:運行本程序文件時執行什么操作
if
__name__
=
=
"__main__"
:
test
=
BlobDataTestor()
try
:
test.setup()
test.testRWBlobData()
test.teardown()
finally
:
test.closedb()
|
到這里python mysql存儲二進制圖片的方法就將完了