Python · SQL Server · Technical Blog

Create a SQL Server Database and Table with Python pyodbc

A complete pyodbc workflow that creates SQF_DB from master, reconnects to the new database, creates dbo.tblEvent only when required, and verifies both objects.

SQL database practical Corrected Python code Create-only-if-missing Furnace event schema

Lab Overview

Python Learning SeriesEstimated time: 45 minutesDifficulty: Intermediate

Prerequisites / What You’ll Need

  • Python 3.x and pyodbc
  • SQL Server instance with database-creation permission
  • Microsoft ODBC Driver 17 or 18
Quick answer

Connect to SQL Server’s existing master database with autocommit=True, run CREATE DATABASE only when DB_ID() returns null, close that connection, then connect to SQF_DB and create dbo.tblEvent only when OBJECT_ID() is null. Commit the table DDL and verify the resulting object ID.

  • You cannot initially connect to a database that does not exist.
  • CREATE DATABASE needs an autocommit connection because it cannot run inside a user transaction.
  • Existence checks make reruns non-destructive, but they do not upgrade an old or incorrect schema.

Python SQL Server Database Creation: What You Will Build

The page covers the exact intent behind “create SQL Server database using Python”: connect to an existing master database, run CREATE DATABASE outside a user transaction, reconnect to the new database, create a table only when missing, and verify the result.

Related Search Topics

pyodbc create database SQL Server · Python create SQL Server table · CREATE DATABASE autocommit pyodbc · connect Python to SQL Server master database

Python pyodbc Database-Creation Workflow

The supplied fragments contain two valid operations but were merged out of order. Database creation and table creation require separate connections because the target database is unavailable until the first operation finishes.

SQL Server Setup • pyodbc Architecture

Python → master → SQF_DB → dbo.tblEvent

Database creation and table creation are two separate DDL stages because Python cannot initially connect to a database that does not yet exist.

1

Python + pyodbc

Load the ODBC interface and connection helper.

import pyodbc connect(...)
2

Connect to master

Open an existing SQL Server database with autocommit for CREATE DATABASE.

connect("master", autocommit=True)
3

Create / Confirm DB

Check DB_ID and create SQF_DB only when missing.

IF DB_ID(...) IS NULL CREATE DATABASE
4

Reconnect SQF_DB

Close the master stage and open the new target database.

connect(DATABASE)
5

Create / Confirm Table

Check OBJECT_ID before creating dbo.tblEvent.

IF OBJECT_ID(...) IS NULL CREATE TABLE
6

Commit & Verify

Commit table DDL and read database/table identity.

connection.commit() DB_NAME() / OBJECT_ID()
masterExisting system database
SQF_DBTarget database
dbo.tblEventFurnace event table
DB_ID / OBJECT_IDExistence checks
Architecture:PythonmasterCREATE DATABASESQF_DBCREATE TABLEVerify

Code-rendered diagram: CREATE DATABASE is separated from CREATE TABLE so each operation runs against a valid connection target.

DDL—Data Definition Language—creates or changes database objects. CREATE DATABASE defines a database; CREATE TABLE defines a table and its columns. This script changes server state and should be executed only by an authorized user against the intended SQL Server instance.

2. Requirements and Permissions

  • Python 3.10 or later.
  • pyodbc: python -m pip install pyodbc.
  • Microsoft ODBC Driver 17 for SQL Server.
  • Network access to SOFTWELL\WINCC.
  • Windows authentication enabled for the executing identity.
  • Server-level permission to create a database and database-level permission to create a table.
Use least privilege: database creation is an administrative operation. In production, a DBA normally provisions the database and grants an application identity only the runtime permissions it needs. Do not run a training script using an unrestricted administrator account.

3. Build a Reusable Connection Helper

def connect(database_name, *, autocommit=False): return pyodbc.connect( f"DRIVER={{{DRIVER}}};" f"SERVER={SERVER};" f"DATABASE={database_name};" "Trusted_Connection=yes;" "TrustServerCertificate=yes;", autocommit=autocommit, timeout=15, )

The helper accepts the database name and transaction mode so the same connection settings can serve both stages. The raw server string preserves the named-instance backslash. Braces around the driver name are required ODBC syntax.

TrustServerCertificate=yes is common in labs using a self-signed certificate. A production server should use a trusted certificate so normal validation can remain enabled.

Create a SQL Server Database from master with pyodbc

with connect("master", autocommit=True) as connection: cursor = connection.cursor() cursor.execute(f""" IF DB_ID(N'{DATABASE}') IS NULL BEGIN CREATE DATABASE [{DATABASE}]; END; """)

DB_ID(N'SQF_DB') returns the database ID when the database exists and NULL otherwise. The conditional prevents a second run from raising “database already exists.”

Autocommit is essential here because SQL Server does not allow CREATE DATABASE inside an explicit user transaction. The operation completes before Python proceeds to the new connection.

5. Reconnect to the New Database

with connect(DATABASE) as connection: cursor = connection.cursor() # CREATE TABLE runs here

A connection remains associated with its original database context. After creating SQF_DB from master, open a new connection whose DATABASE setting is SQF_DB. This also provides a clear failure point if database creation was not successful or access was not granted.

Create a SQL Server Table with Python

IF OBJECT_ID(N'dbo.tblEvent', N'U') IS NULL
BEGIN CREATE TABLE dbo.tblEvent ( DT datetime NOT NULL, TM varchar(10) NULL, SQF_No int NULL, ChargeNo varchar(50) NULL, Event_From varchar(100) NULL, Event_To varchar(100) NULL, Temp_Set float NULL, Temp_Act float NULL, Cp_Set float NULL, Cp_Act float NULL, Oil_Set float NULL, Oil_Act float NULL, Jacket_Set float NULL, Jacket_Act float NULL, Fan_Status varchar(10) NULL );
END;

OBJECT_ID(..., N'U') asks for an object ID specifically for a user table. The condition protects an existing table from being overwritten. It does not compare the existing table’s columns or types; schema migration must be handled separately.

7. Understand the Furnace Event Columns

GroupColumnsPurpose
TimeDT, TMEvent date/time and formatted time text
IdentitySQF_No, ChargeNoFurnace and production-charge references
TransitionEvent_From, Event_ToPrevious and next process stages
TemperatureTemp_Set, Temp_ActSetpoint and actual furnace temperature
Carbon potentialCp_Set, Cp_ActTarget and measured process CP
OilOil_Set, Oil_ActOil process values
JacketJacket_Set, Jacket_ActJacket setpoint and actual value
StatusFan_StatusText status such as ON/OFF

For a production design, consider datetime2 instead of legacy datetime, decimal(p,s) instead of approximate float where exact decimal behavior matters, a primary key, defaults/check constraints, and a single timestamp rather than duplicated DT/TM representations.

8. Commit and Verify the Created Objects

connection.commit() cursor.execute(""" SELECT DB_NAME() AS DatabaseName, OBJECT_ID(N'dbo.tblEvent', N'U') AS TableObjectId;
""")
database_name, table_object_id = cursor.fetchone() if table_object_id is None: raise RuntimeError("dbo.tblEvent was not created.")

The table-creation connection uses normal transaction behavior and explicitly commits. Verification confirms both the active database context and the table object ID. A complete deployment check should additionally query sys.columns for types, lengths, nullability and constraints.

9. Identifier Safety and Idempotent Reruns

SQL parameters such as ? can represent data values, but not database/table identifiers. The database name is therefore interpolated into DDL. This is safe only because DATABASE is a trusted application constant. Never accept an unchecked database name from a web form, command line or file and insert it into SQL text.

The checks make this script create-if-missing: rerunning it leaves existing objects in place. That is useful, but not the same as schema versioning. If an existing tblEvent lacks a column or uses the wrong type, this script reports success without correcting it. Use reviewed migration scripts for schema changes.

10. Complete Corrected Python Program

"""Create SQF_DB and dbo.tblEvent when they do not already exist.""" import pyodbc SERVER = r"SOFTWELL\WINCC"
DATABASE = "SQF_DB"
DRIVER = "ODBC Driver 17 for SQL Server" def connect(database_name, *, autocommit=False): return pyodbc.connect( f"DRIVER={{{DRIVER}}};" f"SERVER={SERVER};" f"DATABASE={database_name};" "Trusted_Connection=yes;" "TrustServerCertificate=yes;", autocommit=autocommit, timeout=15, ) def create_database(): # DATABASE is a trusted constant. SQL identifiers cannot use ? parameters. with connect("master", autocommit=True) as connection: cursor = connection.cursor() cursor.execute(f""" IF DB_ID(N'{DATABASE}') IS NULL BEGIN CREATE DATABASE [{DATABASE}]; END; """) def create_event_table(): with connect(DATABASE) as connection: cursor = connection.cursor() cursor.execute(""" IF OBJECT_ID(N'dbo.tblEvent', N'U') IS NULL BEGIN CREATE TABLE dbo.tblEvent ( DT datetime NOT NULL, TM varchar(10) NULL, SQF_No int NULL, ChargeNo varchar(50) NULL, Event_From varchar(100) NULL, Event_To varchar(100) NULL, Temp_Set float NULL, Temp_Act float NULL, Cp_Set float NULL, Cp_Act float NULL, Oil_Set float NULL, Oil_Act float NULL, Jacket_Set float NULL, Jacket_Act float NULL, Fan_Status varchar(10) NULL ); END; """) connection.commit() def verify_objects(): with connect(DATABASE) as connection: cursor = connection.cursor() cursor.execute(""" SELECT DB_NAME() AS DatabaseName, OBJECT_ID(N'dbo.tblEvent', N'U') AS TableObjectId; """) database_name, table_object_id = cursor.fetchone() if table_object_id is None: raise RuntimeError("dbo.tblEvent was not created.") return database_name, table_object_id def main(): try: create_database() print(f"Database [{DATABASE}] is available.") create_event_table() print("Table [dbo].[tblEvent] is available.") database_name, table_object_id = verify_objects() print(f"Verified database: {database_name}") print(f"Verified table object ID: {table_object_id}") except pyodbc.Error as error: raise SystemExit(f"SQL Server setup failed: {error}") from error if __name__ == "__main__": main()

11. Troubleshooting and Design Improvements

ProblemLikely causeAction
Driver not foundODBC Driver 17 is not installedCheck Windows ODBC Drivers or update DRIVER
Server/instance not foundWrong instance, SQL Browser, firewall or network issueVerify SOFTWELL\WINCC and connectivity
CREATE DATABASE permission deniedWindows identity lacks server permissionAsk the DBA to provision the database or grant approved rights
CREATE DATABASE cannot run in transactionAutocommit was not enabledConnect to master with autocommit=True
Cannot open database requested by loginDatabase missing, offline or user not mappedVerify creation state and grant database access
Table exists but schema is wrongExistence check does not migrate columnsRun a reviewed schema comparison/migration

Recommended production upgrades

  • Use a DBA-managed deployment account separate from the runtime application account.
  • Add a primary key such as Event_ID bigint IDENTITY.
  • Use datetime2 and carefully selected decimal precision/scale.
  • Add check constraints or reference tables for valid fan and process-stage values.
  • Create useful indexes only after studying read/write patterns.
  • Store configuration securely and validate every identifier against an allowlist.
  • Use a migration tool or versioned SQL scripts for future schema changes.

Hands-On Lab: Create and Verify SQF_DB

Hands-on
Before you start
  • Use an approved local or training SQL Server instance.
  • Confirm authorization to create databases and tables.
  • Install pyodbc and the Microsoft ODBC driver.
  • Estimated time: 20 minutes.
1

Test the master connection

Open and close connect("master", autocommit=True) without running DDL.

The authorized Windows identity connects to the intended instance.
2

Create or confirm the database

Run create_database() and verify DB_ID(N'SQF_DB') in SQL Server Management Studio.

SQF_DB exists and a second run does not attempt duplicate creation.
3

Create and inspect the table

Run create_event_table(), then inspect columns and types under SQF_DB → Tables → dbo.tblEvent.

All 15 expected columns are present with the configured types and nullability.
4

Prove idempotent behavior

Run the complete program again and verify it keeps the existing database/table and returns the same table object ID.

The rerun completes without deleting data or recreating objects.

Related Python and SQL Server Tutorials

Continue through the Softwell Python–SQL Server learning path:

Frequently asked questions

Why connect to master first?

The target database does not exist yet, so the initial connection must use an existing database. After creation, open a new connection to SQF_DB.

Why use autocommit for CREATE DATABASE?

SQL Server requires CREATE DATABASE to execute outside an explicit user transaction. Setting autocommit=True on the master connection meets that requirement.

Will the script overwrite an existing database or table?

No. DB_ID() and OBJECT_ID() checks create each object only when missing. However, they do not validate or upgrade an existing table schema.

Reviewed by Bhawesh Kumar SinghIndustrial Automation Trainer and Industry 4.0 Consultant · Softwell Automation · 21+ years industry experience

Get the Python + SQL reporting syllabus

Share your details—a Softwell advisor will contact you with batch dates, fees and project-practice options.

No spam. Used only to share course details for this enquiry.

Build reliable Python and SQL Server projects

Join live online, Pune classroom or corporate Industry 4.0 training.

Request Course Details
Complete Python for Industrial Automation Learning Path

Use Previous / Next for sequential training, or open any topic directly.

Verified learning pathway

Discuss Python SQL Server Training

Explore practical curriculum, software, hardware and batch options for this technology.

Content reviewed: 2 August 2026

☎ Call WhatsApp ✉ Email Enquire Now