Rapportsystem API - of D03N
Hovedprosjekt FiV Programmering 20-24
Loading...
Searching...
No Matches
dataInsertor.py
Go to the documentation of this file.
1from SQLAdminConnections import SQL_AdminConnector as SQLC
2from SQLAdminConnections import SQL_AdminQuerys as SQLQ
3from datetime import datetime, date, time, timedelta
4from decimal import Decimal
5from flask_jwt_extended import get_jwt_identity
6
7#Class for inserting data into a table
9 def __init__(self, table_name, data):
10 self.current_user = get_jwt_identity()
11 # Sets the username, key and database name
12 self.username = self.current_user["email"]
13 self.key = self.current_user["password"]
14 self.db_name = self.current_user["db_name"]
15
16 #Sets the table name and data
17 self.table_name = table_name
18 self.data = data
19
20 def insertData(self):
21 try:
22
23 # Connects to the database server
24 connection = SQLC.SQLConAdmin(None,self.username, self.key,self.db_name)
25 connection.connect()
26
27 # Uses the database
28 query = SQLQ.SQLQueries.use_database(self.db_name)
29 connection.execute_query(query)
30
31 existing_tables = [table[0] for table in connection.execute_query(SQLQ.SQLQueries.show_tables())]
32 if self.table_name not in existing_tables:
33 raise Exception(f"Table {self.table_name} does not exist.")
34
35 #Gets the table description
36 table_description = connection.execute_query(SQLQ.SQLQueries.getTableDescription(self.table_name))
37
38 #converts strings to the correct datatype based on the table description
39 for column_info in table_description:
40 column_name = column_info[0]
41 column_type = column_info[1]
42 if column_name in self.data:
43 if "int" in column_type:
44 self.data[column_name] = int(self.data[column_name])
45 elif "decimal" in column_type:
46 self.data[column_name] = Decimal(self.data[column_name])
47 elif "date" in column_type:
48 self.data[column_name] = datetime.strptime(self.data[column_name], "%Y-%m-%d").date()
49 elif "time" in column_type:
50 self.data[column_name] = datetime.strptime(self.data[column_name], "%H:%M:%S").time()
51 elif "datetime" in column_type:
52 self.data[column_name] = datetime.strptime(self.data[column_name], "%Y-%m-%d %H:%M:%S")
53
54 #Sets data into the table
55 insert_query = SQLQ.SQLQueries.insert_into_table(self.table_name, self.data)
56 connection.execute_query(insert_query)
57 connection.cnx.commit()
58
59 except Exception as e:
60 print(e)
61 connection.cnx.close()
62 connection.close()
63 return {"Error": f"Error when inserting data into the table: {self.table_name}"}
64
65 finally:
66 connection.cnx.close()
67 connection.close()
68 return {"Success": f"Data inserted into the table: {self.table_name}"}