Sure, here is the Python code to list the entire content of a SQL table called establishment
as a web service:
import pyodbcdef list_establishments(): server = "localhost" database = "my_database" username = "sa" password = "my_password" connection_string = "Driver={SQL Server};Server={0};Database={1};Uid={2};Pwd={3}".format( server, database, username, password ) conn = pyodbc.connect(connection_string) cursor = conn.cursor() cursor.execute("SELECT * FROM establishment") establishments = [] for row in cursor: establishment = {} establishment["id"] = row[0] establishment["name"] = row[1] establishment["address"] = row[2] establishment["phone_number"] = row[3] establishments.append(establishment) return establishmentsif __name__ == "__main__": print(list_establishments())
This code will return a list of all establishments in the SQL Server database called my_database
. The list of establishments will be returned as a Python list of dictionaries. Each dictionary will contain the establishment's ID, name, address, and phone number.
To run this code, you will need to have the pyodbc
module installed. You can install the module using the following command:
Once you have installed the module, you can run the code by saving it as a Python script and then running the script from the command line.
For example, to run the code on Windows, you would use the following command:
python list_establishments.py
This will print a list of all establishments in the database to the console.
Here is an explanation of the code:
- The first line imports the
pyodbc
module. This module provides the necessary functionality to connect to a SQL Server database and execute queries. - The next few lines define the connection string to the SQL Server database. The connection string specifies the server name, database name, username, and password for the database.
- The next line creates a connection to the SQL Server database.
- The next line executes a query to get a list of all establishments in the database.
- The final line iterates over the results of the query and creates a dictionary for each establishment. The dictionary contains the establishment's ID, name, address, and phone number.
To run the code, you will need to have a SQL Server database installed and running. You will also need to have the pyodbc
module installed. Once you have installed the module, you can run the code by saving it as a Python script and then running the script from the command line.
I hope this helps! Let me know if you have any other questions.