简体   繁体   中英

PYODBC MS Access Insert Error - Too Few Parameters

I am currently working on a project that takes Tweets and conducts a quick sentiment analysis and loads the tweet ID, the date of the tweet, the text of the tweet, and the tweet's sentiment polarity into an MS Access Table (Office 2013). I've converted the outputs to strings, except for the sentiment polarity to match the table (Test) data types. Here's my code:

from pattern.web import Twitter
import time
import pyodbc
from textblob import TextBlob

cnxn = pyodbc.connect(r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:...SentimentAnalysis.accdb;')
cursor = cnxn.cursor()

s = Twitter().stream('#testhash')
for i in range(25):
    time.sleep(1)
    s.update(bytes=1024)
    if s:
        Ident = str(s[-1].id)
        TweetDate = str(s[-1].date)
        TweetText = str(s[-1].text.encode('utf8'))
        x = s[-1].text
        blob = TextBlob(x)
        sent = blob.sentiment.polarity
        cursor.execute('insert into Test([Ident],[TweetDate],[TweetText],[TweetSentiment]) values (Ident,TweetDate,TweetText,sent);')
        cnxn.commit()
        print 'Inserted: ', Ident
    else: ''
    s.clear()

The problem is that I get the following error:

pyodbc.Error: ('07002', '[07002] [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 4. (-3010) (SQLExecDirectW)')

I've seen other posts on this error, but most have just been due to issues with double quotes in Access. As I have only used single quotes and still get the issue, I am stumped. This is driving me nuts! Any help would be greatly appreciated!

Your SQL statement is including the identifiers Ident , TweetDate , etc., as literal text and the Access Datatabase Engine is considering them to be parameter placeholders. What you need to do is create actual parameter placeholders in your command text and then pass the parameter values . For example:

sql = """\
INSERT INTO [Test] ([Ident], [TweetDate], [TweetText], [TweetSentiment]) 
VALUES (?,?,?,?)
"""
params = (Ident, TweetDate, TweetText, sent)
cursor.execute(sql, params)
cnxn.commit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM