In this section, we explain to you how to create a Database in SQL Server using the Python Programming language with an example.
Before we get into the Python SQL Create DB example query, let me show you the list of available databases in SQL Server.
TIP: Please refer to Connect Python to SQL Server article to understand the steps involved in establishing a connection.
import pyodbc
dbConn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
"Server=PRASAD;"
# "Database=SQL Tutorial;" # Optional (to connectto particluare database
"Trusted_Connection=yes;")
dbCursor = dbConn.cursor()
cursor.execute('SELECT name FROM master.dbo.sysdatabases')
for x in dbCursor:
print('Database = %r' % (x))
The following code will create a new database as the PythonDatabase. You have to follow the same steps whereas the connection information will be different.
import pyodbc
dbConn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
"Server=PRASAD;"
"Database=SQL Tutorial;"
"Trusted_Connection=yes;")
dbConn.autocommit = True
dbCursor = dbConn.cursor()
cursor.execute('CREATE DATABASE [PythonDatabase]')
Now, let me show you the list of available ones to see whether the newly created one is successful or not.
import pyodbc
dbConn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
"Server=PRASAD;"
"Trusted_Connection=yes;")
dbCursor = dbConn.cursor()
cursor.execute('SELECT name FROM master.dbo.sysdatabases')
for x in dbCursor:
print('Database = %r' % (x))
The following are a few of the operations we can do on SQL Server but are not limited to them.