Python database insert

南笙酒味 提交于 2019-12-11 17:59:42

问题


I've been trying to parse a text file (opened with parameter encoding='utf8') and insert extracted values into an mdb database using pyodbc module. I have tried the code below:

for line in fp:
    tokens = line.split('\t')
    tokens[4] = tokens[4][:len(tokens[4])-1] #to avoid the \n
    tokens[1] = tokens[1][1:] #to remove the 'u' from the beginning of utf8 characters like u'\u0622'
    content = conn.execute("INSERT INTO Entries (PForm, WForm, Code, Freq, Pattern) VALUES ("+tokens[0]+","+tokens[1]+","+tokens[2]+","+tokens[3]+","+tokens[4]+")")
    conn.commit()

and received the following error: Error: ('07002', '[07002] [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 4. (-3010) (SQLExecDirectW)')

P.S. the first line of my file is: آ 'A Ab 1 S

And the other lines are of the same format.

Your comments will be appreciated :)


回答1:


You don't put quotes around the strings which you want to insert. Assuming the "Freq" row is of type INTEGER:

stmt = """
INSERT INTO Entries (PForm, WForm, Code, Freq, Pattern)
    VALUES ('%s', '%s', '%s', %s, '%s')
"""

params = tuple(t for t in tokens)

conn.execute(stmt % params)

But anyway, you shouldn't be formatting an INSERT statement like this. Doesn't the library you're using provide a facility to parameterize statements ? Something like this:

conn.execute("INSERT INTO Foo VALUES (?, ?, ?)", (foo, bar, baz))


来源:https://stackoverflow.com/questions/16457781/python-database-insert

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!