In this article, we will show you, How to create a Database in SQL Server using the Python Programming language with an example.
TIP: Please refer Connect Python to SQL Server article to understand the steps involved in establishing a connection.
Before we get into the Python SQL Create DB example query, let me show you the list of available databases in SQL Server.
Python SQL databases
Below program returns all the databases that are available in the current SQL instance. I suggest you refer to SQL Create Database article to understand the query that we used.
# Python SQL Create DB Example import pyodbc dbConn = pyodbc.connect("Driver={SQL Server Native Client 11.0};" "Server=PRASAD;" "Trusted_Connection=yes;") dbCursor = dbConn.cursor() dbCursor.execute("SELECT name FROM master.dbo.sysdatabases") for x in dbCursor: print('Database = %r' %x)
OUTPUT
If you want to work with a particular database then you can specify that database within the connection string.
For example, in the below python program, we used “Database = SQL Tutorial” inside the connection string
# Python SQL Create DB Example import pyodbc dbConn = pyodbc.connect("Driver={SQL Server Native Client 11.0};" "Server=PRASAD;" "Database=SQL Tutorial;" "Trusted_Connection=yes;") dbCursor = dbConn.cursor() dbCursor.execute("SELECT name FROM master.dbo.sysdatabases") for x in dbCursor: print('Database = %r' %x)
OUTPUT
Python SQL Create DB Example
In this example, we will show you, how to create a database in SQL using Python.
Below program creates a new database called PythonDatabase in SQL Server.
# Python SQL Create DB Example import pyodbc dbConn = pyodbc.connect("Driver={SQL Server Native Client 11.0};" "Server=PRASAD;" "Trusted_Connection=yes;") dbConn.autocommit = True dbCursor = dbConn.cursor() dbCursor.execute("CREATE DATABASE [PythonDatabase]")
OUTPUT
Let me run the first query to display the list of databases that are available in a current instance.
From the above screenshot, you can see our newly created Database.