我的数据库命名为:test;表名为:cord; 名为:id的行; X ; y; ž。
让我说我有这样的2D阵列:
asd = [[1.25,2.45,3.65],[2.78,3.59,1.58]......]
我想将asd [0] [0]元素插入x行,asd [0] [1]插入y行,asd [0] [2]插入z行,asd [1] [0]插入x如果我有更多的aray元素,则行,asd [1] [1]进入y行,asd [1] [2]进入z行等等。
到目前为止我的代码(我知道插入函数只定义了x):
import MySQLdb
# Open database connection
db = MySQLdb.connect(host="localhost",port= 3307,user="root",passwd="usbw" , db = "test")
# prepare a cursor object using cursor() method
cur = db.cursor()
# Create table as per requirement
asd = [[1.25,2.45,3.65],[2.78,3.59,1.58]]
for x in asd:
cur.execute("INSERT INTO cord(x) VALUES(%s)",x)
db.commit()
# disconnect from server
db.close()
答案 0 :(得分:2)
你可以一次性地做到这一点"通过executemany()
:
cur.executemany("""
INSERT INTO
cord
(x, y, z)
VALUES
(%s, %s, %s)
""", asd)
db.commit()