☰
Python Across Disciplines
with Python + AI Tool   
×
Table of Contents

1.1.   Introduction 1.2.   About the Author & Contact Info 1.3.   Book Conventions 1.4.   What (Who) is a Programmer? 1.5.   Programming Across Disciplines 1.6.   Foundational Computing Concepts 1.7.   About Python 1.8.   First Steps 1.8.1 Computer Setup 1.8.2 Python print() Function 1.8.3 Comments
2.1. About Data 2.2. Data Types 2.3. Variables 2.4. User Input 2.5. Data Structures (DS)         2.5.1. DS Concepts         2.5.2. Lists         2.5.3. Dictionaries         2.5.4. Others 2.6. Files         2.6.1. Files & File Systems         2.6.2. Python File Object         2.6.3. Data Files 2.7. Databases
3.1. About Processing 3.2. Decisions         3.2.1 Decision Concepts         3.2.2 Conditions & Booleans         3.2.3 if Statements         3.2.4 if-else Statements         3.2.5 if-elif-else Statements         3.2.6 In-Line if Statements 3.3. Repetition (a.k.a. Loops)         3.3.1  Repetition Concepts         3.3.2  while Loops         3.3.3  for Loops         3.3.4  Nested Loops         3.3.5  Validating User Input 3.4. Functions         3.4.1  Function Concepts         3.4.2  Built-In Functions         3.4.3  Programmer Defined Functions 3.5. Libraries         3.5.1  Library Concepts         3.5.2  Standard Library         3.5.3  External Libraries 3.6. Processing Case Studies         3.6.1  Case Studies         3.6.2  Parsing Data
4.1. About Output 4.2. Advanced Printing 4.3. Data Visualization   4.4  Sound
  4.5  Graphics
  4.6  Video
  4.7  Web Output
  4.8  PDFs & Documents
  4.9  Dashboards
  4.10  Animation & Games
  4.11  Text to Speech

5.1 About Disciplines 5.2 Accounting 5.3 Architecture 5.4 Art 5.5 Artificial Intelligence (AI) 5.6 Autonomous Vehicles 5.7 Bioinformatics 5.8 Biology 5.9 Bitcoin 5.10 Blockchain 5.11 Business 5.12 Business Analytics 5.13 Chemistry 5.14 Communication 5.15 Computational Photography 5.16 Computer Science 5.17 Creative Writing 5.18 Cryptocurrency 5.19 Cultural Studies 5.20 Data Analytics 5.21 Data Engineering 5.22 Data Science 5.23 Data Visualization 5.24 Drone Piloting 5.25 Economics 5.26 Education 5.27 Engineering 5.28 English 5.29 Entrepreneurship 5.30 Environmental Studies 5.31 Exercise Science 5.32 Film 5.33 Finance 5.34 Gaming 5.35 Gender Studies 5.36 Genetics 5.37 Geography 5.38 Geology 5.39 Geospatial Analysis ☯ 5.40 History 5.41 Humanities 5.42 Information Systems 5.43 Languages 5.44 Law 5.45 Linguistics 5.46 Literature 5.47 Machine Learning 5.48 Management 5.49 Marketing 5.50 Mathematics 5.51 Medicine 5.52 Military 5.53 Model Railroading 5.54 Music 5.55 Natural Language Processing (NLP) 5.56 Network Analysis 5.57 Neural Networks 5.58 Neurology 5.59 Nursing 5.60 Pharmacology 5.61 Philosophy 5.62 Physiology 5.63 Politics 5.64 Psychiatry 5.65 Psychology 5.66 Real Estate 5.67 Recreation 5.68 Remote Control (RC) Vehicles 5.69 Rhetoric 5.70 Science 5.71 Sociology 5.72 Sports 5.73 Stock Trading 5.74 Text Mining 5.75 Weather 5.76 Writing
6.1. Databases         6.1.1 Overview of Databases         6.1.2 SQLite Databases         6.1.3 Querying a SQLite Database         6.1.4 CRUD Operations with SQLite         6.1.5 Connecting to Other Databases
Built-In Functions Conceptss Data Types Date & Time Format Codes Dictionary Methods Escape Sequences File Access Modes File Object Methods Python Keywords List Methods Operators Set Methods String Methods Tuple Methods Glossary Index Appendices   Software Install & Setup
  Coding Tools:
  A.  Python    B.  Google CoLaboratory    C.  Visual Studio Code    D.  PyCharm IDE    E.  Git    F.  GitHub 
  Database Tools:
  G.  SQLite Database    H.  MySQL Database 


Python Across Disciplines
by John Gordon © 2023

Table of Contents

Table of Contents  »  Chapter 6.1.4 : Connecting to Other Databases

Connecting to Other Databases
Subscribe Contact


Contents

Overview

Connecting to databases to read data from a database, add data to a database or update existing data in a database is a very common task for programmers. On the previous pages we saw how to connect to a SQLite database from Python. Connecting to other database systems is simular, yet with some variation in the methods and code syntax.

Database Connection Concepts

Connecting to a database from Python (or any programming language) is conceptually similar regardless of the database system or the programming language. The difference is how one might connect and some syntactic differences in your code. The overall concept involves, generally, the following steps:

Connecting to SQLite

SQLite is a file-based database system, which means that the database is a file stored on a hard drive somewhere. That location might be on your local computer or on a server or other device.

Figure 1 depicts a development environment set up on a laptop that is not connected to any servers, that is, it is stand-alone.

Figure 2 depicts a development environment set up on a laptop that is connected to a server which might be on a local area network or a cloud-based server.

In either of these configurations, Python is installed on the laptop and we have written a program in Python that we want to connect to the SQLite database named MyDB.db. Here are corresponding examples of Python code to connect to the examples in Figure 1 and Figure 2:

Figure 1: In this case SQLite is installed on the laptop and we store our SQLite databases in the C:\SQLite\Data\ folder.

import sqlite3
connection = sqlite3.connect("C:\SQLite\Data\MyDb.db")
cursor = connection.execute("SELECT * FROM Table;")
# Do the queries and/or CRUD operations here
.
.
.
connection.close()

Figure 1: Python to SQLite Local



Figure 2: Python to SQLite Server
Code Details

Figure 2: In this case SQLite is installed on the server and we store our SQLite databases in the \\ServerName\SharedFolder\Data\ folder.

import sqlite3
connection = sqlite3.connect("\\ServerName\SharedFolder\Data\MyDb.db")
cursor = connection.execute("SELECT * FROM Table;")
# Do the queries and/or CRUD operations here
.
.
.
connection.close()

Code Details

Connecting to MySQL Server

MySQL is a server-based database system, which means MySQL Server runs as a server software in the background on a computer. That server software runs 24/7 (by default) so that the database is always available. It is intended to run on either a physical server or a cloud server that is accessible by multiple users simultaneously. The use of a server-based database system like MySQL Server is normally used in a production system. This is very different than the file-based database SQLite that is just a file stored somewhere. A database server usually requires additional installation steps, maintenance, and has a more robust security layer involved as you'll seen below.

It may seem a bit confusing, but MySQL server can be installed on a local computer (desktop, laptop). The intent of running it on a local computer most of the time is for development and testing. Having it available locally, say on a laptop, allows developers to build programs that will be used in a production system with a full implementation of MySQL Server on a server or in the cloud.

Figure 3 depicts a development environment set up on a laptop that is not connected to any servers, that is, it is stand-alone.

Figure 4 depicts a development environment set up on a laptop that is connected to a server which might be on a local area network or a cloud-based server.

In either of these configurations, Python is installed on the laptop and we have written a program in Python that we want to connect to the MySQL Server database. Here are corresponding examples of Python code to connect to the examples in Figure 3 and Figure 4:

Figure 3: Python to MySQL Server Local



Figure 4: Python to MySQL Server on a Server

Figure 3: In this case MySQL Server is installed on the laptop, as mentioned above, likely for development and testing purposes.

import mysql.connector
myDB = mysql.connector.connect(
  host = "localhost",
  user = "validusername",
  password = "validpassword",
  database = "databasename"
)
cursor = myDB.cursor()
# Do the queries and/or CRUD operations here, like ...
cursor.execute("SELECT * FROM Table;")
result = cursor.fetchall()
.
.
.
myDB.close()

Code Details

  • Code Line 1: First we import the MySQL connector library. This is the connector library for Python to connect to MySQL databases.
  • Code Line 2: This line intializes a variable we'll call myDB and uses the connector library's connect() method to attempt to establish a connection to the MySQL Server.
  • Code Line 3: This line is part of the connect() method and it defines the host, that is, the MySQL Server instance. This is usually localhost in cases such as this example where MySQL Server is installed locally for develoipment and testing.
  • Code Line 4: This line is part of the connect() method and it specifies the user account to us to attempt to connect to the database. User accounts are created in the MySQL Server software itself and access rights appropriate for that user are set there. This differs from SQLite databases that are, by default, open (though this can be changed in SQLite).
  • Code Line 5: This line is part of the connect() method and it specifies the password for the user account that is combined with the username to attempt to connect to the database.
  • Code Line 6: This line specifies the database we want to connect to immediately. Since MySQL is a server-based syste, it can simultaneously host and manage multiple databases at once.
  • Code Lines 2 thru 7 are all part of the MySQL Server connect() method.
  • Code Line 8: This line creates a cursor object based on the MyDB connection.
  • Code Line 9: This line uses the cursor object to execute() a query that will contain the results of the database query inside of the object's execute() method. In this example, that results would be all records from the Table.
  • Code Line 10: This line creates a new variable called result that is an object that holds the results of the execute statement.
  • Code Lines 11 thru 14: This is where we would code the query or CRUD operation steps needed in order to interact with the database.
  • Code Line 15: After all of the database actions are completed we use the connection object's close() method to close the connection to the database. This is an important step to complete our interaction with the database.
Figure 4: In this case MySQL Server is installed and running on a server.

import mysql.connector
myDB = mysql.connector.connect(
  host = "111.111.111.111",
  user = "validusername",
  password = "validpassword",
  database = "databasename"
)
cursor = myDB.cursor()
# Do the queries and/or CRUD operations here, like ...
cursor.execute("SELECT * FROM Table;")
result = cursor.fetchall()
.
.
.
myDB.close()

Code Details

  • Notice that the code for Figure 3 is nearly identical to the code for Figure 4.
  • The difference is in the connect() method where we set the host to the location of the MySQL Server on the server.
  • In this example, we're using an IP address where the server is located.
  • The host address can be an IP address or other valid addressing value.
  • The rest of the code is the same as outlined above for Figure 3.

Connecting to SQL Server

Microsoft SQL Server is a server-based database system, which means it runs as a server software in the background on a computer (usually a server). That server software runs 24/7 (by default) so that the database is always available. It is intended to run on either a physical server or a cloud server that is accessible by multiple users simultaneously. The use of a server-based database system like SQL Server is most often used in a production system. A database server usually requires additional installation steps, maintenance, and has a more robust security layer involved as you'll seen below.

It may seem a bit confusing, but SQL Server can be installed on a local computer (desktop, laptop). The intent of running it on a local computer most of the time is for development and testing. Having it available locally, say on a laptop, allows developers to build programs that will be used in a production system with a full implementation of SQL Server on a server or in the cloud.

Figure 5 depicts a development environment set up on a laptop that is not connected to any servers, that is, it is stand-alone.

Figure 6 depicts a development environment set up on a laptop that is connected to a server which might be on a local area network or a cloud-based server.

In either of these configurations, Python is installed on the laptop and we have written a program in Python that we want to connect to the SQL Server database. Here are corresponding examples of Python code to connect to the examples in Figure 5 and Figure 6:

Figure 3: Python to SQL Server Local



Figure 4: Python to SQL Server on a Server

import pymssql
myDB = pymssql.connect(
host = "localhost",
user = "validusername",
password = "validpassword",
database = "databasename"
)
cursor = myDB.cursor()
# Do the queries and/or CRUD operations here, like ...
cursor.execute("SELECT * FROM Table;")
result = cursor.fetchall()
.
.
.
myDB.close()

Code Details

  • Code Line 1: First we import the pymssql connector library. This is the connector library for Python to connect to SQL Server databases.
  • Code Line 2: This line intializes a variable we'll call myDB and uses the connector library's connect() method to attempt to establish a connection to the SQL Server.
  • Code Line 3: This line is part of the connect() method and it defines the host, that is, the SQL Server instance. This is usually localhost in cases such as this example where SQL Server is installed locally for develoipment and testing.
  • Code Line 4: This line is part of the connect() method and it specifies the user account to us to attempt to connect to the database. User accounts are created in the SQL Server software itself and access rights appropriate for that user are set there.
  • Code Line 5: This line is part of the connect() method and it specifies the password for the user account that is combined with the username to attempt to connect to the database.
  • Code Line 6: This line specifies the database we want to connect to immediately. Since SQL Server is a server-based syste, it can simultaneously host and manage multiple databases at once.
  • Code Lines 2 thru 7 are all part of the SQL Server connect() method.
  • Code Line 8: This line creates a cursor object based on the MyDB connection.
  • Code Line 9: This line uses the cursor object to execute() a query that will contain the results of the database query inside of the object's execute() method. In this example, that results would be all records from the Table.
  • Code Line 10: This line creates a new variable called result that is an object that holds the results of the execute statement.
  • Code Lines 11 thru 14: This is where we would code the query or CRUD operation steps needed in order to interact with the database.
  • Code Line 15: After all of the database actions are completed we use the connection object's close() method to close the connection to the database. This is an important step to complete our interaction with the database.
Figure 6: In this case SQL Server is installed and running on a server.

import pymssql
myDB = pymssql.connect(
host = "111.111.111.111",
user = "validusername",
password = "validpassword",
database = "databasename"
)
cursor = myDB.cursor()
# Do the queries and/or CRUD operations here, like ...
cursor.execute("SELECT * FROM Table;")
result = cursor.fetchall()
.
.
.
myDB.close()

Code Details

  • Notice that the code for Figure 5 is nearly identical to the code for Figure 6.
  • The difference is in the connect() method where we set the host to the location of the SQL Server on the server.
  • In this example, we're using an IP address where the server is located.
  • The host address can be an IP address or other valid addressing value.
  • The rest of the code is the same as outlined above for Figure 3.

Connecting to Cloud Databases

Cloud vendors like Amazon Web Services (AWS), Microsoft Azure, and Google Cloud Services offer many database options as part of their service packages. Since they are cloud-based, any database connections to them require credentials are set up in their cloud system ahead of time--like the MySQL and SQL Server examples above. Also, there can be different connectors for Python depending on which cloud database option you choose. For the purposes of demonstration, I will use AWS RDS as an example here, but remember that some details (particularly the connection aspect) may be different for different database options and cloud system providers. Usually you can find examples of how to connect to those services in their help documentation.

Figure 7 depicts a development environment set up on a laptop that is connected to an AWS server RDS database instance.

import psycopg2
myDB = psycopg2.connect(
host = "your-rds-hostname.us-west-2.rds.amazonaws.com",
port = 5432,
user = "validusername",
password = "validpassword",
database = "databasename"
)
cursor = myDB.cursor()
# Do the queries and/or CRUD operations here, like ...
cursor.execute("SELECT * FROM Table;")
result = cursor.fetchall()
.
.
.
myDB.close()

Figure 3: Python to AWS RDS

Code Details

  • Code Line 1: First we import the psycopg2 connector library. This is the connector library for Python to connect to AWS RDS databases.
  • Code Line 2: This line intializes a variable we'll call myDB and uses the connector library's connect() method to attempt to establish a connection to the AWS RDS.
  • Code Line 3: This line is part of the connect() method and it defines the host, that is, the AWS RDS. Since AWS RDS is cloud-based, the address (endpoint) is dependent on your AWS account and chosen data center.
  • Code Line 4: This line is part of the connect() method and it specifies the user account to us to attempt to connect to the database. User accounts are created in AWS RDS itself and access rights appropriate for that user are set there.
  • Code Line 5: This line is part of the connect() method and it specifies the password for the user account that is combined with the username to attempt to connect to the database.
  • Code Line 6: This line specifies the database we want to connect to immediately. Since AWS RDS is a server-based syste, it can simultaneously host and manage multiple databases at once.
  • Code Lines 2 thru 7 are all part of the AWS RDS connect() method.
  • Code Line 8: This line creates a cursor object based on the MyDB connection.
  • Code Line 9: This line uses the cursor object to execute() a query that will contain the results of the database query inside of the object's execute() method. In this example, that results would be all records from the Table.
  • Code Line 10: This line creates a new variable called result that is an object that holds the results of the execute statement.
  • Code Lines 11 thru 14: This is where we would code the query or CRUD operation steps needed in order to interact with the database.
  • Code Line 15: After all of the database actions are completed we use the connection object's close() method to close the connection to the database. This is an important step to complete our interaction with the database.







© 2023 John Gordon
Cascade Street Publishing, LLC