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 DATABASEneeds 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.
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.
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 hereA 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
| Group | Columns | Purpose |
|---|---|---|
| Time | DT, TM | Event date/time and formatted time text |
| Identity | SQF_No, ChargeNo | Furnace and production-charge references |
| Transition | Event_From, Event_To | Previous and next process stages |
| Temperature | Temp_Set, Temp_Act | Setpoint and actual furnace temperature |
| Carbon potential | Cp_Set, Cp_Act | Target and measured process CP |
| Oil | Oil_Set, Oil_Act | Oil process values |
| Jacket | Jacket_Set, Jacket_Act | Jacket setpoint and actual value |
| Status | Fan_Status | Text 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
| Problem | Likely cause | Action |
|---|---|---|
| Driver not found | ODBC Driver 17 is not installed | Check Windows ODBC Drivers or update DRIVER |
| Server/instance not found | Wrong instance, SQL Browser, firewall or network issue | Verify SOFTWELL\WINCC and connectivity |
| CREATE DATABASE permission denied | Windows identity lacks server permission | Ask the DBA to provision the database or grant approved rights |
| CREATE DATABASE cannot run in transaction | Autocommit was not enabled | Connect to master with autocommit=True |
| Cannot open database requested by login | Database missing, offline or user not mapped | Verify creation state and grant database access |
| Table exists but schema is wrong | Existence check does not migrate columns | Run 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
datetime2and carefully selecteddecimalprecision/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- 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.
Test the master connection
Open and close connect("master", autocommit=True) without running DDL.
Create or confirm the database
Run create_database() and verify DB_ID(N'SQF_DB') in SQL Server Management Studio.
Create and inspect the table
Run create_event_table(), then inspect columns and types under SQF_DB → Tables → dbo.tblEvent.
Prove idempotent behavior
Run the complete program again and verify it keeps the existing database/table and returns the same table object ID.
Related Python and SQL Server Tutorials
Continue through the Softwell Python–SQL Server learning path:
- Python modules, classes and objects
- Python–SQL Server data type mapping
- Create a SQL Server database and table with Python
- Insert data into SQL Server with Python
- Read SQL Server data into pandas
- Complete Python SQL Server CRUD tutorial
- Export SQL Server data to Excel
- Create a Python EXE for WinCC Excel reports
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.
