· 7 years ago · Dec 26, 2018, 05:06 PM
1def create_tweets_table(term_to_search):
2 """
3 This function open a connection with an already created database and creates a new table to
4 store tweets related to a subject specified by the user
5 """
6
7 #Connect to Twitter Database created in Postgres
8 conn_twitter = psycopg2.connect(dbname=dbnametwitter, user=usertwitter, password=passwordtwitter, host=hosttwitter, port=porttwitter)
9
10 #Create a cursor to perform database operations
11 cursor_twitter = conn_twitter.cursor()
12
13 #with the cursor now, create two tables, users twitter and the corresponding table according to the selected topic
14 cursor_twitter.execute("CREATE TABLE IF NOT EXISTS twitter_users (user_id VARCHAR PRIMARY KEY, user_name VARCHAR);")
15
16 query_create = "CREATE TABLE IF NOT EXISTS %s (id SERIAL, created_at timestamp, tweet text NOT NULL, user_id VARCHAR, retweetcount int, PRIMARY KEY(id), FOREIGN KEY(user_id) REFERENCES twitter_users(user_id));" %("tweets_"+term_to_search)
17 cursor_twitter.execute(query_create)
18
19 #Commit changes
20 conn_twitter.commit()
21
22 #Close cursor and the connection
23 cursor_twitter.close()
24 conn_twitter.close()
25 return