gpt4 book ai didi

python 将数组添加到数据库

转载 作者:行者123 更新时间:2023-11-30 01:23:52 25 4
gpt4 key购买 nike

我正在尝试使用 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]]

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

最佳答案

将数组转储到 picklejson。这是比 str() 更好的方法。

关于python 将数组添加到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18227342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com