TypeError和值错误

时间:2016-05-11 21:40:22

标签: python

我有python代码,我可以将数据推送到数据库。

   def push(self, data,lname,mname):
    self.param = data
    self.lname = lname
    self.mname = mname
    # Open database connection
    db = MySQLdb.connect(host = self.dbhost1,port = self.dbport,user = self.dbuser,passwd = self.dbpass , db = self.dbname)

    # prepare a cursor object using cursor() method
    cur = db.cursor()

    # Create table as per requirement
    cur.executemany("""
    INSERT INTO 
        """+ self.lname +"""

    VALUES
        ("""+ self.mname +""", %s, %s, %s)
    ON DUPLICATE KEY UPDATE
        x = VALUES(x),
        y = VALUES(y),
        z = VALUES(z);
    """, self.param)
    db.commit()
    # disconnect from server
    db.close()    

当我尝试推送natom=83

时出现此错误
  d.push(data.natom,"natom","2")
  Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\cclib\bridge\PythonSQL.py", line 46,   in push
""", self.param)
   File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 246, in executemany
    self.errorhandler(self, TypeError, msg)
   File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
 TypeError: 'int' object is not iterable

这个错误下面我得到然后我尝试推动atomcoords =

   [[[1 2 3]
   [1 4 3] 
   [5 6 7]]]

我从量子化学计算的CCLib库得到上面的数组,我没有创建它。但为什么我不能推它呢?

  d.push(data.atomcoords,"xyz","2")
  Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\cclib\bridge\PythonSQL.py", line 46, in push
""", self.param)
  File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 227, in executemany
if not args: return
 ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 

所以如果我尝试推送像这样的数组,我的代码就可以工作。

[[0,2,3],[4,6,3],[5,6,9]]

也许有人知道方式,解决方案或知道一些信息并且可以分享它为什么只能以一种方式工作?我搜索了很多关于这两个错误的解决方案,但没有任何问题可以解决。

1 个答案:

答案 0 :(得分:-1)

根据您的评论和http://cclib.github.io/contents.html,似乎atomcoords是一个numpy arrayexecutemany期望listhttps://docs.python.org/2/library/sqlite3.html) 。请尝试以下代码:

  d.push(data.atomcoords.tolist()[0], "xyz", "2")

http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.ndarray.tolist.html