Basic Usage of SQL Server in a Python Application: A Step-by-Step Guide

In this article, we’ll explore the basic usage of SQL Server in a Python application.In this article, we’ll explore the basic usage of SQL Server in a Python application.

Posted on

SQL Server is a robust and widely-used relational database management system (RDBMS) developed by Microsoft. In this article, we’ll explore the basic usage of SQL Server in a Python application. We’ll cover the steps for connecting to SQL Server, performing common database operations, and handling data using the pyodbc library.

Prerequisites

Before we start, make sure you have the following prerequisites in place:

  1. SQL Server: SQL Server should be installed and running. You can download it from the official Microsoft SQL Server Downloads page.

  2. Python: Make sure you have Python installed on your system. You can download Python from the official Python website.

  3. pyodbc Library: Install the pyodbc package, which is a Python module for connecting to SQL Server. You can install it using pip:

    pip install pyodbc
    

Step 1: Connecting to SQL Server

To use SQL Server in a Python application, you need to establish a connection to the database. Here’s a basic example of how to do this:

import pyodbc

# Database configuration
server = 'your_server_name'
database = 'your_database_name'
username = 'your_username'
password = 'your_password'

# Create a connection
try:
    connection = pyodbc.connect(f'DRIVER=SQL Server;SERVER={server};DATABASE={database};UID={username};PWD={password}')

    if connection:
        print("Connected to SQL Server")

    # Perform database operations here

except pyodbc.Error as e:
    print(f"Error: {e}")

finally:
    if 'connection' in locals():
        connection.close()
        print("Connection closed")

Replace 'your_server_name', 'your_database_name', 'your_username', and 'your_password' with your SQL Server credentials and connection details.

Step 2: Performing Database Operations

Once connected, you can perform various database operations, such as creating tables, inserting data, querying data, updating records, and deleting records. Here are some examples:

Creating a Table

try:
    cursor = connection.cursor()

    create_table_query = """
    CREATE TABLE IF NOT EXISTS users (
        id INT PRIMARY KEY IDENTITY(1,1),
        username NVARCHAR(50) NOT NULL,
        email NVARCHAR(100) NOT NULL
    )
    """

    cursor.execute(create_table_query)
    print("Table 'users' created successfully")

except pyodbc.Error as e:
    print(f"Error: {e}")

finally:
    if 'cursor' in locals():
        cursor.close()

Inserting Data

try:
    cursor = connection.cursor()

    insert_query = "INSERT INTO users (username, email) VALUES (?, ?)"
    data = ("john_doe", "[email protected]")

    cursor.execute(insert_query, data)
    connection.commit()
    print("Data inserted successfully")

except pyodbc.Error as e:
    print(f"Error: {e}")

finally:
    if 'cursor' in locals():
        cursor.close()

Querying Data

try:
    cursor = connection.cursor()

    select_query = "SELECT * FROM users"

    cursor.execute(select_query)

    for row in cursor:
        print(f"ID: {row.id}, Username: {row.username}, Email: {row.email}")

except pyodbc.Error as e:
    print(f"Error: {e}")

finally:
    if 'cursor' in locals():
        cursor.close()

Updating Data

try:
    cursor = connection.cursor()

    update_query = "UPDATE users SET email = ? WHERE username = ?"
    data = ("[email protected]", "john_doe")

    cursor.execute(update_query, data)
    connection.commit()
    print("Data updated successfully")

except pyodbc.Error as e:
    print(f"Error: {e}")

finally:
    if 'cursor' in locals():
        cursor.close()

Deleting Data

try:
    cursor = connection.cursor()

    delete_query = "DELETE FROM users WHERE username = ?"
    data = ("john_doe",)

    cursor.execute(delete_query, data)
    connection.commit()
    print("Data deleted successfully")

except pyodbc.Error as e:
    print(f"Error: {e}")

finally:
    if 'cursor' in locals():
        cursor.close()

Step 3: Error Handling

It’s important to handle errors gracefully when working with databases. In the examples above, pyodbc provides error handling for many common database errors. You can catch and handle exceptions as needed in your application.

Conclusion

In this article, we’ve covered the basic usage of SQL Server in a Python application using the pyodbc library. You’ve learned how to connect to a SQL Server database, create tables, insert data, query data, update records, and delete records. SQL Server is a powerful and widely-used RDBMS, and these fundamental skills will serve as a solid foundation for building more complex database-driven applications with SQL Server and Python.