在python中以单列形式插入数据库中的列表

ve7v8dk2  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(325)

我有一个变量varlist,其中包含list元素,并希望将其插入我的数据库中有两列sess\u id,它是autoincrement和list,在执行此操作时,我希望在其中存储数据:

varlist=["easy"]
    cursor_one.execute("insert into data (list) values(%s)", varlist)
    conn.commit()

我的数据插入正确,但如果我增加varlist中元素的数量:

varlist=["easy","hard","medium"]
    cursor_one.execute("insert into data (list) values(%s)", varlist)
    conn.commit()

我遇到了这个错误:

Traceback (most recent call last):
     File "C:\xampp\htdocs\eclipse_workspace\Project\check.py", line 19, in 
    <module>
     cursor_one.execute("insert into data (list) values(%s)", database_list)
      File "C:\Python34\lib\site-packages\mysql\connector\cursor.py", line 
     553, in execute
     "Not all parameters were used in the SQL statement")
     mysql.connector.errors.ProgrammingError: Not all parameters were used 
     in the SQL statement

这是我的全部密码

import mysql.connector
     conn= mysql.connector.connect
    (user="root",password="",host="localhost",database="videojs")

    varlist=['easy','hard']

    cursor_one.execute("insert into data (list) values(%s)", varlist)
    conn.commit()

请帮帮我。。。。

i2byvkas

i2byvkas1#

我不完全清楚你想达到什么目的。如果要将整个列表插入数据库中的一个“单元格”,则需要将列表转换为字符串表示形式:

import pickle

    varlist=["easy","hard","medium"]
    cursor_one.execute("insert into data (list) values(%s)", pickle.dumps(varlist))
    conn.commit()

但是,如果要将列表中的每个条目放入数据库中自己的行中,则需要遍历列表,为每个条目插入一行:

varlist=["easy","hard","medium"]
    for var in varlist: 
        cursor_one.execute("insert into data (list) values(%s)", var)
    conn.commit()

相关问题