python向数据库添加一个数组

时间:2013-08-14 09:01:12

标签: python mysql numpy

我正在尝试使用h5py从H5文件中获取数组并将它们写入MySQL数据库。 我写了这段代码:

#!/usr/bin/env python
import sys, os, h5py, MySQLdb, numpy

def initial(FileName):
    f = h5py.File(str(FileName), 'r')

    ch1 = f[str("dset1")][:]
    ch2 = f[str("dset2")][:]
    ch3 = f[str("dset3")][:]
    ch4 = f[str("dset4")][:]
    ch5 = f[str("dset5")][:]
    ch6 = f[str("dset6")][:]
    ch7 = f[str("dset7")][:]
    ch8 = f[str("dset8")][:]
    ch9 = f[str("dset9")][:]
    ch10 = f[str("dset10")][:]
    ch11 = f[str("dset11")][:]
    ch12 = f[str("dset12")][:]
    ch13 = f[str("dset13")][:]
    ch14 = f[str("dset14")][:]
    ch15 = f[str("dset15")][:]

    print(numpy.shape(ch1))

    db = MySQLdb.connect(host="localhost", user="myUSR", passwd="myPasswd", db = "myDB")
    cur = db.cursor()
    cur.execute("INSERT INTO myTable (FileName, date, ch1, ch2, ch3, ch4, ch4r, ch5, ch6, ch7, ch8, ch9, ch10, ch11, ch12, Slot, Info) values ( " +
    "\"" + str(FileName) + "\"" +\
    ",\"" +"Bu aralar" + "\"" +\
    ",\"" + ch1 + "\"" +\
    ",\"" + ch2 +  "\"" +\
    ",\"" + ch3 +  "\"" +\
    ",\"" + ch4 + "\"" +\
    ",\"" + ch5 +  "\"" +\
    ",\"" + ch6 +  "\"" +\
    ",\"" + ch7 +  "\"" +\
    ",\"" + ch8 +  "\"" +\
    ",\"" + ch9 +  "\"" +\
    ",\"" + ch10 +  "\"" +\
    ",\"" + ch11 +  "\"" +\
    ",\"" + ch12 +  "\"" +\
    ",\"" + ch13 +  "\"" +\
    ",\"" + ch14 +  "\"" +\
    ",\"" + ch15 +  "\"" + " ) ")
    db.commit()

initial(sys.argv[1])

但是有一个错误告诉我无法将这样的数据写入数据库。所以我试着为每个数据添加srt():

    .
    .
    .
    ",\"" + str(ch4) + "\"" +\
    ",\"" + str(ch5) +  "\"" +\
    ",\"" + str(ch6) +  "\"" +\
    ",\"" + str(ch7) +  "\"" +\
    ",\"" + str(ch8) +  "\"" +\
    ",\"" + str(ch9) +  "\"" +\
    .
    .
    .

但它破坏了我的数据。这就是我的数组在数据库中的样子

[[  0   0   0 ...,   0   0   0]
 [  0   0   0 ...,   0   0   0]
 [  0   0   0 ...,   0   0   0]
 ..., 
 [500 432 472 ...,  46  46  32]
 [309 231 325 ...,  47  47  40]
 [187 236 363 ...,  44  39  39]]

那么请您建议我将数组写入数据库的方法吗?

1 个答案:

答案 0 :(得分:0)

将您的数组转储到picklejson。这是更好的方式,而不是str()