Create a new MS SQL Database

From IronPython Cookbook

The following code uses SMO (SQL Managment Objects) to connect to a remote or local MS SQL Server and create a new blank database. If you want more information on SMO see http://msdn2.microsoft.com/en-us/library/ms162169.aspx.

import sys
import clr
sys.path.append(r"C:\Program Files\Microsoft SQL Server\90\SDK\Assemblies")
clr.AddReferenceToFile('Microsoft.SqlServer.Smo.dll')
import Microsoft.SqlServer.Management.Smo

connectionDBServer = Microsoft.SqlServer.Management.Smo.Server("dbserver.ironpyton.net")
connectionDBServer.ConnectionContext.LoginSecure = 0
connectionDBServer.ConnectionContext.Login = "sa"
connectionDBServer.ConnectionContext.Password = "MyPassword"
print connectionDBServer.Name + " " + connectionDBServer.Information.VersionString
dbNew = Microsoft.SqlServer.Management.Smo.Database(connectionDBServer,"MyTestDatabase")
dbNew.Create()

Notes:

  • If you want to connect to a local database leave the server name off the Smo.Server line.
  • If you want to use Windows Authentication then you don't need the 3 ConnectionContext lines.
  • You will need SQL Server Management Studio installed locally for the script to work.
  • The path in the sys.path.append line needs to point to the correct location where Microsoft.SqlServer.Smo.dll resides on your computer.


Back to Contents.

TOOLBOX
LANGUAGES