TypeError:无法将'list'对象隐式转换为strite SQLite3 Retrieving Data

时间:2015-12-22 00:37:04

标签: python sqlite

def course_id(enrolment_id):
    con = None

    try:
        con = lite.connect('C:/Users/Ethan/Desktop/SAT/SiemensAssessmentTool.db')
        with con:
            cur = con.cursor()

            cur.execute("SELECT course_id FROM Enrolment WHERE enrolment_id = '"+ enrolment_id+ "';")

            rows = cur.fetchall()
            courseids=[]
            for row in (rows):
                courseids = row
                return courseids

    finally:
        if con:
            con.close()

我正在尝试使用此代码检索多个整数,因为我将它连接到另一个函数以从数据库中查找其他数据。我得到的错误是当我将其与其他功能连接时:

def course_name(course_id):
    con = None

    try:
        con = lite.connect('C:/Users/Ethan/Desktop/SAT/SiemensAssessmentTool.db')
        with con:
            cur = con.cursor()

            cur.execute("SELECT course_name FROM Course WHERE course_id = '"+ course_id+ "';")

            rows = cur.fetchall()

            return rows

    finally:
        if con:
            con.close()

我收到了这个错误:

cur.execute("SELECT course_id FROM Enrolment WHERE enrolment_id = '"+ enrolment_id+ "';")
TypeError: Can't convert 'list' object to str implicitly

我猜它与course_id函数有关,但我不确定..提前谢谢

1 个答案:

答案 0 :(得分:2)

  

TypeError:无法转换' list'隐含地反对str

显然,问题是 enrolment_id是一个列表,请检查您将course_id()作为参数传递给什么。

作为旁注,您不应该通过字符串连接构建查询 - 这会导致类型转换出现问题,并使您的代码容易受到SQL injections - 参数化查询的影响:< / p>

cur.execute("SELECT course_id FROM Enrolment WHERE enrolment_id = ?", (enrolment_id, ))

如何获得查询结果也存在问题。假设您需要数据库中的单个课程ID,请使用fetchone()

courseid = cursor.fetchone()[0] 
return courseid