-
Notifications
You must be signed in to change notification settings - Fork 0
/
prsql.py.bak
84 lines (67 loc) · 2.96 KB
/
prsql.py.bak
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
import mysql.connector
from pymongo import MongoClient
# MySQL Database credentials
mysql_db_config = {
'host': '127.0.0.1',
'user': 'vongearthhub_user',
'password': 'Andy@321',
'database': 'osqacademy',
}
# MongoDB credentials
mongo_uri = "mongodb+srv://vongmeetings2:[email protected]/?retryWrites=true&w=majority"
mongo_client = MongoClient(mongo_uri)
mongo_db = mongo_client.get_database("Vongdata")
mongo_collection = mongo_db.get_collection("test3") # Update with the actual collection name
# File to store results
output_file = "result.txt"
try:
# Establish a connection to the MySQL server
mysql_connection = mysql.connector.connect(**mysql_db_config)
if mysql_connection.is_connected():
print("Connected to MySQL database")
# Create a cursor object to execute SQL queries
cursor = mysql_connection.cursor()
# Execute a SELECT query to get the list of usernames from MySQL
query = "SELECT id, username FROM mdl_user"
cursor.execute(query)
# Fetch all the rows
usernames = cursor.fetchall()
# Open the file in append mode
with open(output_file, "a") as result_file:
# Check each username in MongoDB
for username_tuple in usernames:
user_id, username = username_tuple
# Check if the username exists in MongoDB
mongo_query = {"full_name": username}
result = mongo_collection.find_one(mongo_query)
if result:
print(f"Document found in MongoDB for username {username}")
result_file.write(f"Document found for username {username}\n")
else:
print(f"No document found in MongoDB for username {username}")
result_file.write(f"No document found for username {username}\n")
# Insert data into the MongoDB collection
collection = mongo_db['test3'] # Use the Database object
data_to_insert = {
'roll_number': user_id,
'full_name': username,
}
collection.insert_one(data_to_insert)
# Create collections with dynamic names
call = f"{username}_call"
activity = f"{username}_act"
mongo_db.create_collection(call)
mongo_db.create_collection(activity)
except mysql.connector.Error as e:
print(f"Error: {e}")
finally:
# Close the cursor and connection for MySQL
if 'cursor' in locals():
cursor.close()
if 'mysql_connection' in locals() and mysql_connection.is_connected():
mysql_connection.close()
print("MySQL Connection closed")
# Close the connection for MongoDB
if 'mongo_client' in locals():
mongo_client.close()
print("MongoDB Connection closed")