年龄和phone_num是整数值,其余都是字符串。 尝试使用以下代码将其推送到数据库中时,出现以下错误
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无法组合整数和字符串,除非使用str()
显式转换它们
我假设你使用的是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
使用元组模板化到查询中将自动转义字符串并防止 SQL 注入。它还会将您的整数转换为字符串,从而修复您的错误。