((TypeError:使用python环境将数据推入表中时,无法将'int'对象隐式转换为str)

问题描述 投票:0回答:1

Age和phone_num是int值,其余均为字符串。当尝试使用下面的代码将其推入数据库时​​,出现以下错误

insert_query = "insert into employee.details (name,emp_id,age,contact,address) values('"+name+"','"+emp_id+"',"+age+","+phone_num+",'"+address+"')"
    cursor = connection.cursor
    result = cursor.execute(insert_query)
    print("Table updated successfully ")
python arrays int implicit
1个回答
0
投票
我假设您正在使用SQLite3?如果是这样,这是查询的正确语法。

insert_query = """INSERT INTO employee.details (name, emp_id, age, contact, address) VALUES (?, ?, ?, ?, ?)""" cur = conn.cursor() cur.execute(insert_query, (name, emp_id, age, phone_num, address)) one_row = cur.fetchone() # This will only get one row of the data all_data = cur.fetchall() # This will get all rows of data in a list of tuples conn.commit() conn.close() # only if this is last db change

使用tuple进行查询模板化将自动转义字符串并阻止SQL injection。它还会将您的整数转换为字符串,从而修复您的错误。

© www.soinside.com 2019 - 2024. All rights reserved.