-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathinsert-test.py
79 lines (63 loc) · 2.47 KB
/
insert-test.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
import mysql.connector
from mysql.connector import Error
from mysql.connector import errorcode
import time
import os
AURORA_NODE1 = os.environ['AURORA_NODE1']
AURORA_NODE2 = os.environ['AURORA_NODE2']
DB_NAME = "demo"
DB_USER = "admin"
DB_PASSWORD = "cloudacademy"
def reconnect(connection):
try:
connection.reconnect()
print("reconnection succeeded...")
except:
print("reconnection failed...")
try:
connection1 = mysql.connector.connect(host=AURORA_NODE1,
database=DB_NAME,
user=DB_USER,
password=DB_PASSWORD)
connection2 = mysql.connector.connect(host=AURORA_NODE2,
database=DB_NAME,
user=DB_USER,
password=DB_PASSWORD)
sql = "INSERT INTO course (title, instructor, duration, created, url) VALUES (%s, %s, %s, %s, %s)"
for x in range(100):
courseTitle = "Title{}".format(x)
data = (courseTitle, 'Jeremy Cook', 100, '1999-03-30', 'http://here.com')
#connection load balancing logic
if x % 2 == 0:
connection = connection1
connection_backup = connection2
else:
connection = connection2
connection_backup = connection1
try:
cursor = connection.cursor()
cursor.execute(sql, data)
connection.commit()
print(cursor.rowcount, "record inserted successfully [{}]...".format(connection.server_host))
cursor.close()
#connection retry logic
except mysql.connector.errors.Error:
cursor = connection_backup.cursor()
cursor.execute(sql, data)
connection_backup.commit()
print(cursor.rowcount, "record inserted (BACKUP) successfully [{}]...".format(connection_backup.server_host))
cursor.close()
if not connection1.is_connected():
reconnect(connection1)
if not connection2.is_connected():
reconnect(connection2)
time.sleep(0.5)
except Error as error:
print("Failed to insert record into table: {}".format(error))
finally:
if (connection1.is_connected()):
connection1.close()
print("connection1 is closed")
if (connection2.is_connected()):
connection2.close()
print("connection2 is closed")