How to insert / retrieve a file stored as a BLOB in a MySQL db using python

橙三吉。 提交于 2019-11-27 13:41:06
thedata = open('thefile', 'rb').read()
sql = "INSERT INTO sometable (theblobcolumn) VALUES (%s)"
cursor.execute(sql, (thedata,))

That code of course works as written only if your table has just the BLOB column and what you want to do is INSERT, but of course you could easily tweak it to add more columns, use UPDATE instead of INSERT, or whatever it is that you exactly need to do.

I'm also assuming your file is binary rather than text, etc; again, if my guesses are incorrect it's easy for you to tweak the above code accordingly.

Some kind of SELECT on cursor.execute, then some kind of fetching from the cursor, is how you retrieve BLOB data, exactly like you retrieve any other kind of data.

You can insert and read BLOBs from a DB like every other column type. From the database API's view there is nothing special about BLOBs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!