SQLite Where子句语法错误

时间:2017-04-23 00:46:45

标签: python sqlite csv

我正在使用Python创建一个包含多个CSV文件数据的SQLite数据库。从文件A,我已成功创建一个表并向该表添加了条目。我想从文件B向数据库添加其他列。文件A和文件B中的行不匹配,但它们需要在数据库中匹配。

我为代码的长度道歉 - 我从CSV文件中选择特定的行来添加到数据库中。我在这里包含了所有代码,以防上下文有用。

此代码有效:

with open('/Users/Leo/Desktop/accord_key.csv','rU') as accord_csv:
     accord_csv_reader = csv.reader(accord_csv)
    for row in accord_csv_reader:
        MaskID = row[0]
        female = row[1]
        age = row[2]
        arm = row[3]
        cvd_hx_baseline = row[6]
        female = int(female)
        age = float(age)
        arm = int(arm)
        cvd_hx_baseline = int(cvd_hx_baseline)

        if age < 50: continue
        if ((arm == 5) or (arm == 6) or (arm == 7) or (arm == 8)): continue
        female = str(female)
        age = str(age)
        arm = str(arm)
        cvd_hx_baseline = str(cvd_hx_baseline)
        cur.execute('INSERT OR IGNORE INTO accord_baseline (MaskID) VALUES (?)',
                (MaskID,)
                )
        cur.execute('UPDATE OR IGNORE accord_baseline SET female = '+female+' WHERE MaskID=?',
                (MaskID,)
                )
        cur.execute('UPDATE OR IGNORE accord_baseline SET age = '+age+' WHERE MaskID=?',
                (MaskID,)
                )
        cur.execute('UPDATE OR IGNORE accord_baseline SET arm = '+arm+' WHERE MaskID=?',
                (MaskID,)
                )
        cur.execute('UPDATE OR IGNORE accord_baseline SET cvd_hx_baseline = '+cvd_hx_baseline+' WHERE MaskID=?',
                (MaskID,)
                )
        age = float(age)
        if age >= 75:
            cur.execute('UPDATE OR IGNORE accord_baseline SET age_75 = 1 WHERE MaskID=?',
                    (MaskID,)
                    )
    conn.commit()
    accord_csv.close()

此代码不起作用:

with open('/Users/Leo/Desktop/otherlabs.csv','rU') as labs_csv:
    labs_csv_reader = csv.reader(labs_csv)
    count = 0
    for row in labs_csv_reader:
        MaskID = row[0]
        visit = row[1]
        gfr = row[7]
        if visit == 'BLR':
            cur.execute('UPDATE OR IGNORE accord_baseline SET mdrd = '+gfr+' WHERE MaskID=?',
                    (MaskID,)
                    )
    conn.commit()
    labs_csv.close()

由于我无法通过搜索找到答案,所以感谢您提供的任何帮助!!

1 个答案:

答案 0 :(得分:1)

在您的情况下,这可能是也可能不是问题 - 您只是正确执行了一半的转义,因此如果您的数据中存在',则SQL查询可能会被破坏。

不要这样做:

cur.execute('UPDATE OR IGNORE accord_baseline SET mdrd = '+gfr+' WHERE MaskID=?',
    (MaskID,))

请改为:

cur.execute('UPDATE OR IGNORE accord_baseline SET mdrd = ? WHERE MaskID=?',
    (gfr, MaskID))