Click here to Skip to main content
15,889,838 members
Articles / Web Development / ASP.NET

Create SQL Server Database using asp.net

Rate me:
Please Sign up or sign in to vote.
2.50/5 (12 votes)
27 Oct 20072 min read 90.5K   1.8K   32  
Here I am showing, How to Create SQL Database and Run SQL Script File Using asp.net.
Imports Microsoft.SqlServer
Imports Microsoft.SqlServer.Management.Smo
Imports Microsoft.SqlServer.Management.Common.ConnectionManager

Partial Class _Default
    Inherits System.Web.UI.Page

    Dim objDBCreate As DatabaseCreator
    Dim ConnStr As String = ""
    Dim IsDBCreated As Boolean = False

    Protected Sub Wizard1_FinishButtonClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.WizardNavigationEventArgs) Handles Wizard1.FinishButtonClick
        If Wizard1.ActiveStep.Name = "Run SQL Script" Then

            Dim sqlpath As String = Server.MapPath(txtSQLPath.Text)
            objDBCreate = New DatabaseCreator

            '======== First Create the Connection String from Previous Steps Settings
            Dim StrCon As String = ""
            If Not ViewState("ConStr") Is Nothing Then
                StrCon = ViewState("ConStr") & "Database=" & txtDBName.Text & ";"
            End If
            '========= Run the SQL Script
            If objDBCreate.ExecuteSQLScript(sqlpath, StrCon) Then
                CreateMessageAlert(Me.Page, "SQL Script Execute Successfully..", "Run")
            Else
                CreateMessageAlert(Me.Page, "There is an error into script file", "notrun")
            End If

        End If
    End Sub

    Protected Sub Wizard1_NextButtonClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.WizardNavigationEventArgs) Handles Wizard1.NextButtonClick
        '======== Create Database
        If Wizard1.ActiveStep.Name = "Database Configuration" Then
            '========= Check DB Exits or not
            If CheckAndCreateDatabase(txtServer.Text, txtUserID.Text, txtPassword.Text, txtDBName.Text) = True Then
                IsDBCreated = True
                CreateMessageAlert(Me.Page, "Database Created Successfully.", "Created")
            Else
            End If
        End If
    End Sub

    Private Function CheckAndCreateDatabase(ByVal servername As String, ByVal userid As String, ByVal password As String, ByVal database As String) As Boolean
        
        If TestConnection(servername, userid, password, database) = True Then
            'check Server name and database name are not empty.
            If servername <> "" And database <> "" Then
                Dim oServer As New Server
                Dim oServerConnection As New Management.Common.ServerConnection(servername)

                oServerConnection.ConnectionString = ConnStr
                oServerConnection.Connect()

                oServer = New Server(oServerConnection)

                Dim db As New Database

                '========= check for DB Existance
                For Each db In oServer.Databases
                    If database = db.Name Then
                        CreateMessageAlert(Me.Page, "The database already exist, try with another name..", "Database")
                        Return False
                    End If
                Next

                'create the database procedure goes here.
                objDBCreate = New DatabaseCreator

                If objDBCreate.CreateSQLDb(txtServer.Text, txtDBName.Text, txtUserID.Text, txtPassword.Text) = True Then
                    ViewState.Add("ConStr", ConnStr)
                    Return True
                Else
                    Return False
                End If
            Else
                Return False
            End If
        End If

    End Function

    Private Function TestConnection(ByVal servername As String, ByVal userid As String, ByVal password As String, ByVal databasename As String) As Boolean
        'check for windows authentication mode.
        If ddlAuthenticationMode.SelectedValue = 1 Then
            ConnStr = "Persist Security Info=False;Integrated Security=SSPI;Data Source=" & servername & ";"
        End If
        'check for sql server authentication mode.
        If ddlAuthenticationMode.SelectedValue = 0 Then
            ConnStr = "Persist Security Info=False;User ID=" & userid & ";pwd=" & password & ";Data Source=" & servername & ";"
        End If

        Dim str As String = ConnStr

        Dim Conn As New Data.SqlClient.SqlConnection
        Conn.ConnectionString = ConnStr

        If Conn.State = Data.ConnectionState.Closed Then
            Conn.Open()
            Return True
        Else
            CreateMessageAlert(Me.Page, "Test connection failed for Server : " & txtServer.Text, "Database")
            Return False
        End If
    End Function

    Protected Sub ddlAuthenticationMode_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlAuthenticationMode.SelectedIndexChanged
        If ddlAuthenticationMode.SelectedValue = 0 Then
            RequiredFieldValidator3.Enabled = True
            RequiredFieldValidator4.Enabled = True
            txtUserID.Enabled = True
            txtPassword.Enabled = True
        Else
            RequiredFieldValidator3.Enabled = False
            RequiredFieldValidator4.Enabled = False
            txtUserID.Enabled = False
            txtPassword.Enabled = False
        End If
    End Sub

    Public Shared Sub CreateMessageAlert(ByRef aspxPage As System.Web.UI.Page, _
                               ByVal strMessage As String, ByVal strKey As String)
        Dim strScript As String = "<script language=JavaScript>alert('" _
                                            & strMessage & "')</script>"

        If (Not aspxPage.ClientScript.IsStartupScriptRegistered(strKey)) Then
            aspxPage.ClientScript.RegisterStartupScript(GetType(String), strKey, strScript)
        End If
    End Sub

End Class

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Team Leader
India India
Jatin is Working in .Net Technology Since 2006. He has Completed Master of Science Degree in Information Technology. He Likes to learn Cutting edge technologies. He has good Skills in Asp.net, Vb.net,C#.Net, Crystal Reports,GDI+, Ajax, WCF, Silverlight SQL Server,IIS Admin,TFA ,Application Architecture Designing.

Comments and Discussions