forked from Vincelogs/DB_Script
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch_data.py
More file actions
61 lines (49 loc) · 1.56 KB
/
fetch_data.py
File metadata and controls
61 lines (49 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import psycopg2
import json
# Function to query the database and fetch data
def fetch_data(names):
# Connect to the PostgreSQL database
conn = psycopg2.connect(
dbname='mayan',
user='mayan',
password='password',
host='192.168.100.36'
)
cursor = conn.cursor()
# Initialize result list
result = []
# Query the database for each name
for name in names:
# Execute the query
cursor.execute("SELECT id, label FROM public.cabinets_cabinet WHERE label = %s", (name,))
row = cursor.fetchone()
# If a record is found, store the id and label in the result list
if row:
result.append({'id': row[0], 'label': row[1]})
else:
print(f"No record found for {name}")
# Close the database connection
conn.close()
return result
# List of names to query the database
# Read names from CSV file
# names_to_query = []
# with open('names.csv', 'r') as csvfile:
# csvreader = csv.reader(csvfile)
# for row in csvreader:
# names_to_query.extend(row)
# Read names from TXT file
names_to_query = []
with open('names.txt', 'r') as txtfile:
for line in txtfile:
names_to_query.append(line.strip())
# Fetch data from the database
data = fetch_data(names_to_query)
# Convert the data to the desired format
formatted_data = [
{ 'id': entry['id'], 'label': entry['label'] } for entry in data
]
# Export the data as a JSON file
with open('data.json', 'w') as f:
json.dump(formatted_data, f, indent=4)
print("Data exported successfully.")