user15847315
user15847315

Reputation:

insert in database table in python

im a beginner in python and i have this project where i neeed to classify tweets into different categories i have created a tweet table in mysql database that contains these following attributes:(tweet_id,id_user,text,tweet_location,created_at,name_screen, categorie_name) where they will be inserted by the informations in every tweet that corresponds to them

but i keep receiving this error :

 line 43, in <module>
    data['user_screen_name'],data['cat'])
KeyError: 'cat'

data['cat'] is already declared in another program witch executes the classification in the same directory

do i need to connect the two programs or ? any help would be really appreciated

import mysql.connector
import json
# create the key

mydb = mysql.connector.connect(host='localhost', port='3306', user='root', password='nihad147', database='tweets')
mycursor = mydb.cursor()

sql_tweet = """INSERT INTO tweet (  tweet_id,
                                    id_user,
                                    text,
                                    tweet_location,
                                    created_at,
                                    name_screen,
                                    categorie_name,
                                    )
                                    VALUES (%s,%s,%s,%s,%s,%s,%s)"""
c = 0
for line in myJsonFile:
    c = c + 1
    print("tweet number ", c, " is uploading to the server")
    data = json.loads(line)
    # insert into tweet



    val_tweet = (
        data['tweet_id'], data['user_id_str'], data['raw_text'], data['location']['address']['city'], data['date'],
        data['user_screen_name'],data['cat'])
    print('nihad')
    mycursor.execute(sql_tweet, val_tweet)

    mydb.commit()

Upvotes: 1

Views: 76

Answers (1)

omid akhgary
omid akhgary

Reputation: 41

you need to debug you're code you can add

print(data)

before insert into tweet to find out document keys and values

also you can use from data.get("date", None) instead of data["date"] this code returns None value if date key no exists instead of raise error

Upvotes: 0

Related Questions