【问题标题】:Python insert array elements into mysql databasePython将数组元素插入mysql数据库
【发布时间】:2018-08-16 05:29:22
【问题描述】:

我正在处理图像并转换成大约 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)

但我仍然遇到同样的错误。

【问题讨论】:

    标签: python mysql


    【解决方案1】:

    对于您的错误 - %s 只能用于格式化字符串参数,但您的一些参数是 int 类型 - 因此是类型错误。

    看起来您正在尝试构建数据框并将其上传到 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')
    

    【讨论】:

      猜你喜欢
      • 2014-12-26
      • 2019-12-05
      • 1970-01-01
      • 1970-01-01
      • 2011-12-24
      • 1970-01-01
      • 2011-07-05
      • 1970-01-01
      相关资源
      最近更新 更多