Search code snippets, questions, articles...

تنفيذ سكربت لانشاء قاعدة برمجيا

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ExecutesqlFile("(local)", "TestTestD", Application.StartupPath & "\SQLScript.sql")
    End Sub
    Public Sub ExecutesqlFile(ByVal SERVAR_NAME_SQL As String, ByVal DATABASE_NAME As String, ByVal sqlFile As String)
        Using connection As New SqlClient.SqlConnection("Server =" & SERVAR_NAME_SQL & ";database=" & DATABASE_NAME & ";integrated security=true")
            If connection.State = ConnectionState.Closed Then connection.Open()
            Dim sql As String = ""
            Using strm As FileStream = File.OpenRead(sqlFile)
                Dim reader As New StreamReader(strm)
                sql = reader.ReadToEnd()
            End Using
            Dim regex As New Regex("^GO", RegexOptions.IgnoreCase Or RegexOptions.Multiline)
            Dim lines As String() = regex.Split(sql)
            Dim transaction As SqlClient.SqlTransaction = connection.BeginTransaction()
            Using cmd As SqlClient.SqlCommand = connection.CreateCommand()
                cmd.Connection = connection
                cmd.Transaction = transaction
                ProgressBar1.Step = 1
                For Each line As String In lines
                    If line.Length > 0 Then
                        ProgressBar1.Maximum = line.Length + 20
                        ProgressBar1.Value = line.Length
                        cmd.CommandText = line
                        cmd.CommandType = CommandType.Text
                        Try
                            cmd.ExecuteNonQuery()
                        Catch generatedExceptionName As SqlClient.SqlException
                            MsgBox(generatedExceptionName.Message, MsgBoxStyle.Critical, "")
                            transaction.Rollback()
                            Throw
                        End Try
                    End If
                Next
                ProgressBar1.Value = ProgressBar1.Maximum
                MsgBox("تمت عملية انشاء الجداول و الاستعلامات بنجاح", MsgBoxStyle.Information, "")
            End Using
            transaction.Commit()
            connection.Close()
        End Using
    End Sub
Was this helpful?
0 Comments
Programming Feeds
Learn something new everyday on Devsheet