Question

FLASK _SQLALCHAMY_Microsot SQL Server - Executing Multiline Query

As i was following below tutorial :How To Build Web Applications with Flask Not found any good suggestion on below query.

Want to connect and execute below SQL statement on MS SQL Server (microsoft) from Flask web application.

SQL QUERY 1:
"""
USE [TESTDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [INSIM\MY14AT].[TestTable](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[col1] [varchar](10) NULL,
	[col2] [varchar](10) NULL
) ON [PRIMARY]
GO
"""
SQL QUERY 2:
'
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Arun
-- Create date: 2024-04-27
-- Description:	Test SP
-- =============================================
ALTER PROCEDURE dbo.sp_TestSP 
	@p1 VARCHAR(10)
	,@p2 VARCHAR(10)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT * From TestTable where col1=@p1 and col2=@p2
	SELECT * From TestTable where col1=@p1 
END
GO
'
SQL QUERY 3 : Exec sp_TestSP @p1,@p2
  • Returns multiple result set. Any suggestion on drivers/plugins and sample code will be well appreciated.

With Thanks, Arun. patro.arun@gmail.com


Submit an answer


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

KFSys
Site Moderator
Site Moderator badge
April 28, 2024

Heya @adorableceruleaneel,

To connect to a Microsoft SQL Server database from a Flask web application and execute SQL queries, including those for creating tables, altering procedures, and running stored procedures, you’ll need to use the appropriate Python libraries and handle database connections securely. Here’s a guide to set this up using pyodbc, a popular Python SQL Server database interface:

Step 1: Install Necessary Packages

First, you need to install Flask and pyodbc. If you haven’t already installed these, you can do so using pip:

pip install Flask pyodbc

Step 2: Configure Database Connection

To connect to your SQL Server, you’ll need to configure the connection string. Ensure that you have the necessary drivers installed on your system (e.g., ODBC Driver for SQL Server).

Here is a sample Flask application that sets up a connection to SQL Server:

from flask import Flask, jsonify, request
import pyodbc

app = Flask(__name__)

# Database configuration
server = 'your_server_address'
database = 'TESTDB'
username = 'your_username'
password = 'your_password'
driver = '{ODBC Driver 17 for SQL Server}'  # Adjust as per your driver version

# Connection string
conn_str = f'DRIVER={driver};SERVER={server};DATABASE={database};UID={username};PWD={password}'

# Function to execute a query
def execute_query(query):
    with pyodbc.connect(conn_str) as conn:
        with conn.cursor() as cursor:
            cursor.execute(query)
            if cursor.description:  # Checking if it's a SELECT query
                columns = [column[0] for column in cursor.description]
                results = [dict(zip(columns, row)) for row in cursor.fetchall()]
                return results
            else:
                conn.commit()  # Commit for INSERT, UPDATE, DELETE
                return None

@app.route('/create-table')
def create_table():
    query = """
    SET ANSI_NULLS ON;
    SET QUOTED_IDENTIFIER ON;
    CREATE TABLE TestTable (
        Id int IDENTITY(1,1) NOT NULL,
        col1 varchar(10) NULL,
        col2 varchar(10) NULL
    ) ON [PRIMARY];
    """
    execute_query(query)
    return jsonify({"message": "Table created successfully"})

@app.route('/alter-procedure')
def alter_procedure():
    query = """
    SET ANSI_NULLS ON;
    SET QUOTED_IDENTIFIER ON;
    ALTER PROCEDURE dbo.sp_TestSP
        @p1 VARCHAR(10),
        @p2 VARCHAR(10)
    AS
    BEGIN
        SET NOCOUNT ON;
        SELECT * FROM TestTable WHERE col1 = @p1 AND col2 = @p2;
        SELECT * FROM TestTable WHERE col1 = @p1;
    END;
    """
    execute_query(query)
    return jsonify({"message": "Procedure altered successfully"})

@app.route('/execute-procedure')
def execute_procedure():
    p1 = request.args.get('p1')
    p2 = request.args.get('p2')
    query = f"EXEC sp_TestSP @p1 = '{p1}', @p2 = '{p2}'"
    result = execute_query(query)
    return jsonify(result)

if __name__ == '__main__':
    app.run(debug=True)

Step 3: Adjust Queries and Use

  • Remove GO Statements: Python doesn’t understand SQL’s GO command. It’s a batch separator used in SQL Server Management Studio, not part of the SQL language. Separate commands should be executed separately if needed.
  • Security Considerations: Avoid SQL injection by using parameterized queries, especially for data manipulation based on user input.
  • Multi-Statements Handling: For handling multiple statements or more complex transaction controls, you may need to manage transactions explicitly using pyodbc’s transaction control features.

Step 4: Running Your Flask Application

Run your Flask app by executing the Python script. Make sure to replace placeholders in the connection string with actual values.

python your_flask_app.py

You can then access endpoints defined in your Flask app to perform SQL operations. This setup provides a basic framework, and you might need to expand or adjust it based on your specific requirements, such as handling complex transactions or optimizing for performance.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Featured on Community

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel