Insert numpy array into MySQL database via Python /Habr
If you encounter a problem that can't normally save numpy array to MySQL database. then this note is for you! The original post was published in my blog is .
I chose for myself a way to save through the module. pickle . With it, you can safely save a numpy array of any dimension in the blob of the MySQL database.
So, an example code:
import numpy as np
# We are connected to our database
connection = mysql.connector.connect (host = 'localhost',
database = 'database',
user = 'root',
password = '')
# Create a cursor
cursor = connection.cursor ()
# Create a test table with one field of type blob
query = 'create table test (`column` blob);'
# Create a numpy
array. array = np.array ([[1,2,3],[4,5,6]])
# Insert our array into the table using the pickle.dumps
transform. query = 'insert into test values (% s);'
db_array = pickle.dumps (array)
cursor.execute (query,[db_array ])
# Select all rows from the test
table. query = 'select * from test;'
res = cursor.fetchall ()
# We look at the result
## We got this thing:[(bytearray(b'x80x03cnumpy.core.multiarrayn_reconstructnqx00cnumpynndarraynqx01Kx00x85qx02Cx01bqx03x87qx04Rqx05(Kx01Kx02Kx03x86qx06cnumpyndtypenqx07Xx02x00x00x00i8qx08Kx00Kx01x87qtRqn(Kx03Xx01x00x00x00
In this way, you can exchange numpy multidimensional (and regular) numpy arrays between Python and MySQL in an absolutely unhindered fashion. If you read the image using cv2.imread from the OpenCV library, for example, then the principle remains the same - because it is, in fact, a multidimensional array.
I hope this helps someone to solve a similar problem!
It may be interesting
find the best coffee maker
best websites for coffee lovers