@@ -14,6 +14,44 @@ def get_database_credentials():
14
14
}
15
15
16
16
17
+ def compare_users_rows (r1 , r2 ):
18
+ # Do something
19
+ print ("Comparing rows..." )
20
+
21
+
17
22
if __name__ == '__main__' :
18
- with pyodbc .connect (MYSQL_CONNECTION_FORMAT .format (** get_database_credentials ())) as conn :
19
- print ("SUCCESS" )
23
+ _connection_string = MYSQL_CONNECTION_FORMAT .format (** get_database_credentials ())
24
+
25
+ # This is a special API in Python, which allows opening a connection for example,")
26
+ # without taking care of closing it. It closes itself outside of its scope.")
27
+ with pyodbc .connect (_connection_string ) as conn :
28
+ # In order to query the database we need to create a cursor.")
29
+ # The cursor is part of the db api, which means every database handler uses it.")
30
+ # The cursor is like an open socket inside a connection, so we must ensure to close it")
31
+ with conn .cursor () as cur :
32
+ # Now we can execute queries on the database
33
+ cur .execute ("SELECT * FROM {tbl}" .format (tbl = config .get ("MySQL" , "users_table_name" )))
34
+ first_row = cur .fetchone ()
35
+ second_row = cur .fetchone () # will return None if no results left to fetch
36
+ # third_row etc...
37
+ other_rows = cur .fetchall () # will return all the *other* results
38
+
39
+ # Let's says we now need to process the results, therefore we should close the cursor. Cursor=Resources
40
+ # So continue writing outside the with-cursor-scope
41
+ compare_users_rows (first_row , second_row )
42
+ compare_users_rows (other_rows [0 ], other_rows [1 ])
43
+ # Now we want to insert a row, so we need a cursor
44
+ with conn .cursor () as cur :
45
+ cur .execute (
46
+ "INSERT INTO {tbl} (username, email, password) values ('default', 'default', 'default');"
47
+ .format (tbl = config .get ("MySQL" , "users_table_name" ))
48
+ )
49
+ # Don't forget to commit
50
+ conn .commit ()
51
+ # Now to close the connection, we simply write outside the with-connection-scope
52
+ print ("Closing database connection" )
53
+ print ("Exiting..." )
54
+
55
+
56
+
57
+
0 commit comments