[英]Python insert array elements into mysql database
I am processing images and converting into around 400 data values. 我正在处理图像并将其转换为约400个数据值。 I want each one of these values to be stored in a column.
我希望将这些值中的每一个存储在一列中。 My mysql table has got columns like these:
我的mysql表有这样的列:
MYID, WIDTH, HEIGHT,P1,P2,P3.....P400.
I can easily save these into a csv file, but since the processing happens on around 3 million files I thought I will write these output directly to a mysql table instead of creating multiple csv files. 我可以轻松地将它们保存到一个csv文件中,但是由于处理发生在大约300万个文件中,我想我将直接将这些输出写入mysql表中,而不是创建多个csv文件。
This is what I have written so far: 到目前为止,这是我写的:
for (i, imagePath) in enumerate(imagePaths):
filename = imagePath[imagePath.rfind("/") + 1:]
image = cv2.imread(imagePath)
rows, cols, channels = image.shape
if not image is None:
features = detail.describe(image)
features = [str(x) for x in features]
fileparam = [filename,cols,rows]
sqldata = fileparam+features
var_string = ', '.join('?' * len(sqldata))
query_string = 'INSERT INTO lastoneweeknew VALUES (%s)' % var_string
y.execute(query_string, sqldata)
If I print sqldata, it gets printed like this: 如果我打印sqldata,它将像这样打印:
['120546506.jpg',650, 420, '0.0', '0.010269055',........., '0.8539078']
The mysql table has these data types: mysql表具有以下数据类型:
+----------+----------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+----------------+------+-----+---------+----------------+
| image_id | int(11) | NO | PRI | NULL | auto_increment |
| MYID | int(10) | YES | | NULL | |
| WIDTH | decimal(6,2) | YES | MUL | NULL | |
| HEIGHT | decimal(6,2) | YES | MUL | NULL | |
| P1 | decimal(22,20) | YES | | NULL | |
| P2 | decimal(22,20) | YES | | NULL | |
When I insert the data into mysql table I am getting the following error: 当我将数据插入mysql表时,出现以下错误:
TypeError: not all arguments converted during string formatting
However, when I write the output to csv file and insert the csv data into mysql using R, I could insert without any trouble. 但是,当我将输出写入csv文件并使用R将csv数据插入mysql时,可以轻松插入。
I thought the row and column values are integers and the rest looks like text in the output and hence I converted them to text. 我以为行和列的值是整数,其余的看起来像输出中的文本,因此我将它们转换为文本。
row = str(rows)
col = str(cols)
But I am still getting the same error. 但是我仍然遇到同样的错误。
For your error - %s can only be used to format string arguments, but some of your arguments are int types - thus the type error. 对于您的错误-%s仅可用于格式化字符串参数,但是您的某些参数为int类型-因此类型错误。
It looks like you are trying to build a data frame and upload it to a MySQL database - luckily this is a common task so there is a library called pandas that can do this all for you. 看起来您正在尝试构建数据框架并将其上传到MySQL数据库-幸运的是,这是一项常见的任务,因此有一个名为pandas的库可以为您完成所有这些工作。 If you create a list of dictionaries where each of the dictionarys key-value pairs are ColumnName: Value.
如果您创建字典列表,其中每个字典的键值对都是ColumnName:Value。
import pandas as pd
from pandas.io import sql
import MySQLdb
def handlePaths(imagePaths):
imageDataList = []
for (i, imagePath) in enumerate(imagePaths):
filename = imagePath[imagePath.rfind("/") + 1:]
image = cv2.imread(imagePath)
rows, cols, channels = image.shape
if not image is None:
features = detail.describe(image)
features = [str(x) for x in features]
fileparam = [filename,cols,rows]
sqldata = fileparam+features
imageData = {"MYID" : value,
"WIDTH" : value,
"HEIGHT": value,
"P1": value, #I would do these iterivly
.....,
"P400": value}
imageDataList.append(imageData)
imageDataFrame = pd.DataFrame(imageDataList)
database_connection = MySQLdb.connect() # may need to add some other options to connect
imageDataFrame.to_sql(con=database_connection, name='lastoneweeknew', if_exists='replace')
I assume this is a pretty cpu-consuming process, you could assign an image to each cpu to make it run quicker, By uploaded each individual entry you let the database handle the race conditions. 我认为这是一个非常消耗CPU的过程,您可以为每个CPU分配一个映像,以使其运行更快。通过上载每个单独的条目,您可以让数据库处理竞争条件。
import pandas as pd
from pandas.io import sql
import MySQLdb
import multiprocessing
def analyzeImages(imagePaths) #imagePaths is a list of image paths
pool = multiprocessing.Pool(cpu_count)
pool.map(handleSinglePath, imagePaths)
pool.join()
pool.close()
def handleSinglePath(imagePath):
image = cv2.imread(imagePath) #Not sure what you where doing before here but you can do it again
rows, cols, channels = image.shape
if not image is None:
features = detail.describe(image)
features = [str(x) for x in features]
fileparam = [filename,cols,rows]
sqldata = fileparam+features
imageData = {"MYID" : value,
"WIDTH" : value,
"HEIGHT": value,
"P1": value, #I would do these iterivly
.....,
"P400": value}
imageDataFrame = pd.DataFrame(imageData)
database_connection = MySQLdb.connect() # may need to add some other options to connect
imageDataFrame.to_sql(con=database_connection, name='lastoneweeknew', if_exists='replace')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.