Python 'ndarray' 无法转换为 MySQL 类型

Python 'ndarray' cannot be converted to a MySQL type

我正在尝试使用 python 脚本将一些数据存储在 MYSQL 数据库中,但出现以下错误。

mysql.connector.errors.ProgrammingError: Failed processing format-parameters;
Python 'ndarray' cannot be converted to a MySQL type

实际上我正在从 netCDF 文件中提取变量并试图将它们存储在 MYSQL 数据库中。我的代码是

import sys
import collections
import os
import netCDF4
import calendar
from netCDF4 import Dataset
import mysql.connector
from mysql.connector import errorcode

table = 'rob-tabl'
con = mysql.connector.connect(user='rob', password='xxxx',
                                  database=roby)
cursor = con.cursor()


smeData = """
        CREATE TABLE rob-tabl (
        `id` bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY,
        `time.val` double,
        `time.microsec` double,
        `temp.degrees` double,
        `humid.calc` double,
        `pressure.calc` double;"""

这些是我在 mMYSQL 数据库中的字段/列名称。我正在尝试将 netCDF4 数据插入 MYSQL

smeData = "INSERT INTO `" + table + "` "
.
.
.
.
.
.
.
.

data_array = []
for item in totfiles.items(): # loop on different netCDF files in a                      directory , but at the moment I had only one file
    nc = Dataset('filename', 'r')
    data1 = nc.variables['time'][:]
    data2 = nc.variables['microsec'][:]
    data3 = nc.variables['temperature'][:]
    data4 = nc.variables['humidity'][:]
    data5 = nc.variables['pressure'][:]
    data = data1 + data2 + data3 + data4 + data5
    data_array.append(data)
    print 'data_array: ', data_array
    cursor.execute(smeData, data_array)

或者如果我尝试像这样组合所有变量

data_array = []
for item in totfiles.items():
    nc = Dataset('filename', 'r')
    data1 = nc.variables['time'][:]
    data2 = nc.variables['microsec'][:]
    data3 = nc.variables['temperature'][:]
    data4 = nc.variables['humidity'][:]
    data5 = nc.variables['pressure'][:]
    data = ([(data1).tolist(), (data2).tolist(), data3.tolist(), data4.tolist(), data5.tolist()])
    data_array.append(data)
    print type(data)
    for v in data:
        cursor.executemany(smeData, (v,))

当我打印 netCDF 变量数据时,例如时间变量,它看起来像 这个

nc.variables['time'][:] # netCDF variable

我明白了

[1302614127 1302614137 1302614147 ..., 1302614627 1302614647 1302614657]

微秒看起来像

 [0 0 0 ..., 0 0 0]

而 data_array 看起来像

data_array=  [[1302614127 1302614137 1302614147 ..., 1302614627 1302614647
 1302614657], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [21, 22,34,34....,67,55], [12.2, 12.54, 12.55....,45.54,45.48], [0,0,0...,0,0,00]]

但是如果我打印

for v in data:
    print v 

然后我只得到列表中的第一个列表,而不是其他列表,我想这是我的主要问题。

[1302614127 1302614137 1302614147 ..., 1302614627 1302614647 1302614657]

如果我尝试执行 cursor.executemany(smeData, (v,)) 命令,它会给我这个错误

mysql.connector.errors.ProgrammingError: Not all parameters were used in 
the SQL statement

我的 MYSQL 插入语法是 我的 MYSQL 语法是

"INSERT INTO `rob-tabl` (`time.val`,`time.microsec`,`temp.degrees`,
`humid.calc`,`pressure.calc`) VALUES (%s,%s,%s,%s,%s)"

在我的例子中是 numpy.float32。我在 MYSQL 中创建了 5 列,我不得不将数据从 netCDF 存储到数据库中。
我是编程新手,正在学习。如果有人帮助我或给我一些提示,我该如何处理这样的错误。我将非常感激。 非常感谢。

使用 sqlite3 而不是 MYSQL,但我认为 sql 会很相似

In [709]: import sqlite3
In [711]: conn=sqlite3.connect(":memory:")

定义一个简单的 3 字段 table:

In [714]: conn.execute('create table test (x, y, z)')
Out[714]: <sqlite3.Cursor at 0xa943cb20>

定义一个numpy数组,4'rows',3'columns'

In [716]: data = np.arange(12).reshape(4,3)
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])

tolist 将其转换为数字列表的列表:

In [735]: data.tolist()
Out[735]: [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]

我可以将它插入到 table 中:

In [719]: conn.executemany('insert into test values (?,?,?)',data.tolist())
Out[719]: <sqlite3.Cursor at 0xa93dfae0>

并测试插入:

In [720]: for row in conn.execute('select x,y,z from test'):
     ...:     print(row)
     ...:     
(0, 1, 2)
(3, 4, 5)
(6, 7, 8)
(9, 10, 11)

因此它已将 data.tolist() 的每个子列表写为 table 中的一条记录。

我猜您想将 5 个字段写入数据库,对应于每个 Dataset.

中的 data1data2

为了获得更多帮助,我建议包括 create 命令,仅使用一个 Dataset 进行测试,并显示(或汇总)您尝试插入的 dataarray .

另一种创建兼容列表的方法是:

In [736]: data = [np.arange(3).tolist(),np.arange(10,13).tolist(),np.arange(20,23).tolist()]
In [737]: data
Out[737]: [[0, 1, 2], [10, 11, 12], [20, 21, 22]]
In [738]: conn.executemany('insert into test values (?,?,?)',data)
Out[738]: <sqlite3.Cursor at 0xa93df320>
In [739]: for row in conn.execute('select x,y,z from test'):
     ...:     print(row)
     ...:     
....
(0, 1, 2)
(10, 11, 12)
(20, 21, 22)

mysql.connector.errors.ProgrammingError: Failed processing format-parameters;Python 'list' cannot be converted to a MySQL type 中,您正在尝试保存包含 5 个列表的列表,每个子列表包含 2000 个项目。让我们扩展我的示例。

我有 (3,10) data 数组

In [881]: data
Out[881]: 
array([[  0,   1,   2,   3,   4,   5,   6,   7,   8,   9],
       [ 10,  11,  12,  13,  14,  15,  16,  17,  18,  19],
       [100, 101, 102, 103, 104, 105, 106, 107, 108, 109]])

data.tolist() 将构成一个 3 元素列表,包含 10 个元素子列表。

In [884]: conn.executemany('insert into test values (?,?,?)',data.tolist())
---------------------------------------------------------------------------
ProgrammingError                          Traceback (most recent call last)
<ipython-input-884-6788d19a96ab> in <module>()
----> 1 conn.executemany('insert into test values (?,?,?)',data.tolist())

ProgrammingError: Incorrect number of bindings supplied. The current statement uses 3, and there are 10 supplied.

sqlite3 给出的错误与您的 MYSQL 不同,但我认为根本问题是相同的 - 尝试将 10 元素列表或元组写入 3 字段记录。

但是如果我先转置数组,我会得到一个包含 10 个子列表的列表

In [885]: conn.executemany('insert into test values (?,?,?)',data.T.tolist())
Out[885]: <sqlite3.Cursor at 0xa6c850a0>
In [886]: for row in conn.execute('select x,y,z from test'):
     ...:     print(row)
....
(0, 10, 100)
(1, 11, 101)
(2, 12, 102)
(3, 13, 103)
(4, 14, 104)
(5, 15, 105)
(6, 16, 106)
(7, 17, 107)
(8, 18, 108)
(9, 19, 109)

转置列表是:

In [887]: data.T.tolist()
Out[887]: 
[[0, 10, 100],
 [1, 11, 101],
 ...
 [9, 19, 109]]

'transposing' 列表的一个众所周知的 Python 习语使用 zip。它实际上生成了一个元组列表,这可能是一件好事。

In [888]: list(zip(*data))
Out[888]: 
[(0, 10, 100),
 (1, 11, 101),
 (2, 12, 102),
 ....
 (8, 18, 108),
 (9, 19, 109)]

元组列表更容易格式化:

for row in data.T.tolist():
    print('%s,%s,%s'%tuple(row))
for row in zip(*data):
    print('%s,%s,%s'%row)