问题
I have a piece of code here which captures an image from my internal webcam on my laptop. With this image, i would like to directly send it to my MySQL database. here is the code.
import numpy as np
import cv2
import mysql.connector
from mysql.connector import errorcode
from time import sleep
import serial
# Obtain connection string information from the portal
config = {
'host':'oursystem.mysql.database.azure.com',
'user':'user',
'password':'pass',
'database':'projectdb'
}
try:
conn = mysql.connector.connect(**config)
print("Connection established")
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with the user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
cursor = conn.cursor()
cursor.execute("CREATE TABLE if not exists Camera (img BLOB);")
cap = cv2.VideoCapture(0)
# Check if the webcam is opened correctly
if not cap.isOpened():
raise IOError("Cannot open webcam")
frame = cap.read()[1]
cursor.execute("INSERT INTO Camera (img) VALUES %s",frame)
cap.release()
As you guys can see, I am trying to directly send the image that is captured and stored in the variable 'frame' to my database, but it isn't working. Any ideas?
回答1:
You want:
cursor.execute("INSERT INTO Camera (img) VALUES(%s)",(frame,))
This being said, storing images in a SQL database is seldom a good idea - but if you really want to do so, at least add a primary key to your table.
EDIT : from your comments, it looks like frame
is a numpy.ndarray
. Your database connector does not know how to convert each and any python type to something the database will understand, so you have to manually convert your frame
to a byte string (bytes
in Python3, str
in Python2).
来源:https://stackoverflow.com/questions/47906056/store-captured-image-in-mysql-database-with-python-and-opencv