Connect to databases - lvphj/epydemiology GitHub Wiki
Function that allows database login details to be entered on-the-fly to enable connection to databases without the need to hard-code details into code.
phjConnectToDatabase()
def phjConnectToDatabase(phjDBType,
phjMaxAttempts = 3,
phjPrintResults = False):
Description
This function was written to meet two main needs: i) enable database login details to be entered on-the-fly (without the need to hard-code login details in a script), and ii) when login details are entered at a terminal, it's not uncommon for there to be typing errors in the entered information and, therefore, this function allows several attempts to enter the correct data (default number of attempts is 3) before aborting (this is useful if a database needs to be accessed in the middle of a long script because if means that incorrect entry of connection details does not require the whole script to be re-run from the beginning).
The function allows connection to MySQL and SQL SERVER databases. To make the connections, the function makes use of pymysql and pymssql libraries which, therefore, need to be installed in the Python environment. The user will be prompted to enter all other required parameters including server address, username and password details.
Function parameters
-
phjDBType
Identifies the type of database to which the connection should be made. Can be 'mysql' or 'mssql'; at present, no other details are allowable.
-
phjMaxAttempts (default = 3)
Maximum number of attempts to enter datails.
-
phjPrintResults (default = False)
Indicates whether the results should be printed to screen as the function progresses. However, in this function it has no effect; it is included simply to ensure the function follows a standardised format template.
Exceptions raised
None
Returns
This function returns a connection object to a database.
Other notes
None
Example
An example of the function in use is given below:
# The pymysql and pymssql libraries will be automatically imported if
# installed in Python environment; the imports are given here to
# emphasise that additional libraries need to be installed.
import pymysql # only required if connecting to MySQL database
import pymssql # only required if connecting to SQL SERVER database
import epydemiology as epy
tempConn = epy.phjConnectToDatabase('mysql')
print(tempConn)
This prints the following:
<pymysql.connections.Connection object at 0x1c1cd94b10>