Skip to content

Instantly share code, notes, and snippets.

@gongfan99
Created May 27, 2023 03:53
Show Gist options
  • Save gongfan99/acc5b89fba60c2b533632e68db7a5fe5 to your computer and use it in GitHub Desktop.
Save gongfan99/acc5b89fba60c2b533632e68db7a5fe5 to your computer and use it in GitHub Desktop.
save embeddings as BLOB in MySQL with Python
import numpy as np
import mysql.connector
cnx = mysql.connector.connect(
host="HOST",
port=3306,
user="USERNAME",
password="PASSWORD",
database="DATABASE NAME",
pool_name="mypool",
pool_size=5,
)
cursor = cnx.cursor()
embeddings = [0.6, 0.8]
# save embeddings as BLOB in example_table
query="INSERT INTO example_table (embeddings) VALUES (%s)"
buf = np.array(embeddings, dtype=np.float32).tobytes()
params = (buf,)
cursor.execute(query, params)
id = cursor.lastrowid
cnx.commit()
# read back embeddings from the table
query="SELECT embeddings FROM example_table WHERE id = %s"
params = (id,)
cursor.execute(query, params)
rows = cursor.fetchall()
buf = rows[0][0]
arr = np.frombuffer(buf, dtype=np.float32)
cnx.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment