Python MSSQL: Create Database – Step-by-Step Guide with Code Examples
Last updated 1 month ago | 101 views 75 5

Creating and managing databases programmatically is a critical skill for developers and data engineers. With Python and Microsoft SQL Server (MSSQL), you can automate database creation, configuration, and maintenance using libraries like pyodbc
.
This article walks you through the process of creating a new database in MSSQL using Python — complete with step-by-step instructions, code snippets, a full working example, and helpful tips.
Prerequisites
Before getting started, ensure the following are set up:
✅ Required Software:
-
Python 3.7+
-
Microsoft SQL Server (Local or Remote)
-
ODBC Driver for SQL Server installed
-
SQL Server Authentication credentials (or Windows Authentication)
✅ Required Python Package:
Install the pyodbc
package:
pip install pyodbc
Step 1: Install and Verify the ODBC Driver
Before connecting, make sure your system has the correct ODBC driver installed.
Check installed drivers:
import pyodbc
print(pyodbc.drivers())
Look for a driver like "ODBC Driver 17 for SQL Server"
or "ODBC Driver 18 for SQL Server"
.
Step 2: Establish a Connection to the Server
You need to connect to the server level — not a specific database — in order to run CREATE DATABASE
.
SQL Server Authentication Example:
server = 'localhost'
username = 'your_username'
password = 'your_password'
conn = pyodbc.connect(
f"DRIVER={{ODBC Driver 17 for SQL Server}};"
f"SERVER={server};"
f"UID={username};"
f"PWD={password};"
)
Windows Authentication Example:
conn = pyodbc.connect(
"DRIVER={ODBC Driver 17 for SQL Server};"
"SERVER=localhost;"
"Trusted_Connection=yes;"
)
Step 3: Create the Database
Now that you're connected, use SQL to create a database. You do not need to specify a database in the connection string — just connect to the server.
Create Database Query:
cursor = conn.cursor()
db_name = "EmployeeDB"
create_db_query = f"CREATE DATABASE {db_name}"
cursor.execute(create_db_query)
conn.commit()
print(f"Database '{db_name}' created successfully.")
Full Example – Create MSSQL Database Using Python
import pyodbc
# Connection settings
server = 'localhost'
username = 'your_username'
password = 'your_password'
database_name = 'EmployeeDB'
try:
# Connect to the server (not a specific DB)
conn = pyodbc.connect(
f"DRIVER={{ODBC Driver 17 for SQL Server}};"
f"SERVER={server};"
f"UID={username};"
f"PWD={password};"
)
cursor = conn.cursor()
# SQL command to create a new database
cursor.execute(f"CREATE DATABASE {database_name}")
conn.commit()
print(f"Database '{database_name}' created successfully.")
except pyodbc.Error as e:
print("Error occurred:", e)
finally:
cursor.close()
conn.close()
Tips for Success
✅ Use Parameterized Inputs Carefully
When creating databases dynamically, ensure the name is valid and doesn't allow SQL injection. Always validate user input.
✅ Ensure Permissions
The SQL login used must have permission to execute CREATE DATABASE
. If not, you will receive a "permission denied" error.
✅ Avoid Re-Creation Errors
Check if a database already exists before trying to create it:
cursor.execute(f"""
IF NOT EXISTS (SELECT name FROM sys.databases WHERE name = '{database_name}')
CREATE DATABASE {database_name}
""")
✅ Handle Case Sensitivity
SQL Server is case-insensitive by default, but be cautious when using custom collations.
⚠️ Common Pitfalls
Issue | Cause | Solution |
---|---|---|
"Login failed for user" | Wrong credentials or no access | Double-check username/password, and server authentication mode |
"CREATE DATABASE permission denied" | User lacks proper permissions | Use a user with dbcreator or sysadmin role |
"Database already exists" | Duplicate create attempt | Add a condition to check existence before creating |
"Cannot open database requested by the login" | Trying to connect to a DB before it's created | Connect to the server only, not to a DB in the connection string |
Conclusion
Creating a Microsoft SQL Server database using Python is simple with the pyodbc
library and a valid server connection. This automation can be integrated into setup scripts, CI/CD pipelines, or database provisioning tools. Just be sure to manage permissions carefully and validate inputs when dealing with dynamic SQL operations.