ValueError:基数为10的int()的无效文字:'SOH'

时间:2011-01-21 04:41:06

标签: python sqlite

当我尝试将值插入sqlite数据库时,我收到以下错误

Traceback (most recent call last):
  File "C:\SS\Problem13\src\database.py", line 23, in <module>
    sql = """INSERT INTO students (name, student_id, email, school_id, gender, gpa, address) VALUES ('%s','%i','%s','%i','%s','%f','%s')"""%(data[0], int(data[1]),data[2],int(data[3]),data[4],float(data[5]),data[6])
ValueError: invalid literal for int() with base 10: 'SOH'

以下是我的代码:

import sqlite3
import csv
# Connect to database, if it does not exist, it will create it.
conn = sqlite3.connect("nopoly.db")
# Creating table.
conn.execute("PRAGMA foreign_keys = 1")
conn.execute("CREATE TABLE schools (id INTEGER PRIMARY KEY, name TEXT NOT NULL, description TEXT NOT NULL, director TEXT NOT NULL, email TEXT NOT NULL)")
conn.execute("CREATE TABLE students (id INTEGER PRIMARY KEY, name TEXT NOT NULL, student_id INTEGER NOT NULL, email TEXT NOT NULL, school_id INTEGER NOT NULL REFERENCES schools, gender TEXT NOT NULL, gpa FLOAT NOT NULL, address TEXT NOT NULL)")
# Opening the csv files
schoolreader = csv.reader(open("files/schools.csv"))
studentreader = csv.reader(open("files/studentsp13.csv"))
# Skip the headers
schoolreader.next()
studentreader.next()
# Extract each row and print
for data in schoolreader:
    print data
    sql = """INSERT INTO schools (name, description, director, email) VALUES ('%s','%s','%s','%s')"""%(data[0],data[1],data[2],data[3])
    print "DEBUG", sql
    conn.execute(sql)
for data in studentreader:
    print data
    sql = """INSERT INTO students (name, student_id, email, school_id, gender, gpa, address) VALUES ('%s','%i','%s','%i','%s','%f','%s')"""%(data[0], int(data[1]),data[2],int(data[3]),data[4],float(data[5]),data[6])
    print "DEBUG", sql
    conn.execute(sql)
#
conn.commit()

据我所知,在studentsp13.csv中,学校被标记为字符串。我想知道如何将它映射成整数,使其对应于“学校”表。

1 个答案:

答案 0 :(得分:4)

  

当我尝试将值插入sqlite数据库时,我收到以下错误

您应该将它们作为参数传递给conn.execute()方法,而不是使用字符串格式将参数插入到查询中。通过这样做,您可以保护自己免受SQL注入攻击,并且数据被数据库视为正确的类型。 SQLite python docs提供了有关如何执行此操作的详细信息和示例。

  

据我所知,在studentsp13.csv中,学校被标记为字符串。我想知道如何将它映射成整数,使其对应于“学校”表。

当您将条目插入Schools表时,您可以将SQLite生成的ID记录到字典中,然后在插入学生条目时再次查找它们。这看起来像这样:

schools = {}
for data in schoolreader:
    print data
    sql = """INSERT INTO schools (name, description, director, email) VALUES ('%s','%s','%s','%s')"""%(data[0],data[1],data[2],data[3])
    conn.execute(sql)
    schools[data[0]] = conn.lastrowid
for data in studentreader:
    school_id = schools[data[3]]
    sql = """INSERT INTO students (name, student_id, email, school_id, gender, gpa, address) VALUES ('%s','%i','%s','%i','%s','%f','%s')"""%(data[0], int(data[1]),data[2],school_id,data[4],float(data[5]),data[6])
    conn.execute(sql)