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

时间:2018-01-14 19:17:16

标签: python mysql sql list sqlite

我有变量varlist,它有list元素,想把它插入我的db中 有两列sess_id是自动增量和列表,我想存储数据 当我这样做时:

    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()

请帮帮我....

1 个答案:

答案 0 :(得分:0)

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

    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()