python将数组元素插入mysql数据库

wf82jlnq  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(521)

我正在处理图像并转换成大约400个数据值。我希望这些值中的每一个都存储在一列中。我的mysql表有如下列:

MYID, WIDTH, HEIGHT,P1,P2,P3.....P400.

我可以很容易地将它们保存到一个csv文件中,但是由于处理发生在大约300万个文件上,我想我会将这些输出直接写入mysql表,而不是创建多个csv文件。
这是我迄今为止写的:

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)

如果我打印sqldata,它会这样打印:

['120546506.jpg',650, 420, '0.0', '0.010269055',........., '0.8539078']

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    |                |

当我将数据插入mysql表时,出现以下错误:

TypeError: not all arguments converted during string formatting

但是,当我将输出写入csv文件并使用r将csv数据插入mysql时,我可以毫无困难地插入。
我认为行和列的值是整数,其余的看起来像输出中的文本,因此我将它们转换为文本。

row = str(rows)
col = str(cols)

但我还是犯了同样的错误。

kokeuurv

kokeuurv1#

对于错误-%s只能用于格式化字符串参数,但某些参数是int类型-因此类型错误。
看起来您正在尝试构建一个Dataframe并将其上载到mysql数据库-幸运的是这是一个常见的任务,因此有一个名为pandas的库可以为您完成所有这些。如果创建字典列表,其中每个字典的键值对都是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')

我假设这是一个相当消耗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')

相关问题