-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMySQL_Add.py
94 lines (74 loc) · 2.79 KB
/
MySQL_Add.py
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import mysql.connector
import json
# Function to connect to the MySQL database and add one record to the database """
# Database variables:
database_name = "djangowebsite" # the name of the target database
table_name = "airtrafficapp_aircrafts"
# import database_credentials as dbkeys
with open("/etc/config.json") as config_file:
config = json.load(config_file)
# Create a function to connect to the MYSQL server
def database_connect(hostname, username, password, database=database_name):
mydb = mysql.connector.connect(
host=hostname, user=username, passwd=password, database=database
)
return mydb
# Return an object containing the MYSQL connection
mydb = database_connect(
config.get("MYSQL_HOSTNAME"),
config.get("MYSQL_USERNAME"),
config.get("MYSQL_PASSWORD"),
)
print(mydb)
# Create the cursor to manipute databases
my_cursor = mydb.cursor()
my_cursor.execute(
f"SELECT * FROM {database_name}.{table_name} ORDER BY id DESC LIMIT 1;"
)
for records in my_cursor:
print(records)
print(records[0])
# Create place holders records to insert into the table
sqlStuff = f"""INSERT INTO {table_name} (icao24,
callsign,
origin_country,
time_position,
last_contact,
longitude,
latitude,
baro_altitude,
on_ground,
velocity,
true_track,
vertical_rate,
sensors,
geo_altitude,
squawk,
spi,
position_source,
time)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s,%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) """
# Save the record to the database
# single element at the time
def add_to_database(data):
try:
# Add records to the database
my_cursor.execute(sqlStuff, data)
# Commit changes to the database
mydb.commit()
# print('Record Added to DB')
except:
print("Error Saving to DB")
mydb.close()
# Save the record to the database with
# multiple records at the same time
def add_many_database(data):
try:
# Add records to the database
my_cursor.executemany(sqlStuff, data)
# Commit changes to the database
mydb.commit()
print("Record Added to DB")
except:
print("Error Saving to DB")
mydb.close()