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 :)
-
Can you put a raw line from the text file and the "Entries" schema?Antonio Beamud– Antonio Beamud2013年05月09日 09:00:40 +00:00Commented May 9, 2013 at 9:00
-
The text file contains many lines, each line contains five tokens separated by a tab. The three first lines are like: آ 'A Ab 1 S\n برآ barA V1 5000 WS\n بوآ bo'A N1 1 WS\nuser3017348– user30173482013年05月09日 09:07:09 +00:00Commented May 9, 2013 at 9:07
-
and the table "Entries" has exactly five columns as indicated in the 5th line of my codeuser3017348– user30173482013年05月09日 09:10:30 +00:00Commented May 9, 2013 at 9:10
-
can you print tokens before the execute and post here the output?Antonio Beamud– Antonio Beamud2013年05月09日 09:27:18 +00:00Commented May 9, 2013 at 9:27
-
[u'\u0622', u'A', u'Ab', u'1', u'S']user3017348– user30173482013年05月09日 09:55:35 +00:00Commented May 9, 2013 at 9:55
1 Answer 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))