| Rubrik: Datenbanken | VB-Versionen: VB2022 | 17.11.25 |
Physischen Namen einer SQL-Datenbank ermittelnDie gezeigte Funktion ermittelt den physischen Namen einer SQL-Datenbank als Tuple (Pfad, Filename) | ||
| Autor: | Bewertung: | Views: 107 |
| ohne Homepage | System: Win7, Win8, Win10, Win11 | kein Beispielprojekt |
Mit diesem Tipp lässt sich der physische name einer SQL-Datenbank schnell ermitteln.
Hier die Funktion: Servername und Datenbankname als Parameter:
''' <summary> ''' SQL-Abfrage, um den physischen Dateinamen zu erhalten ''' </summary> ''' <param name="serverName">der ServerName</param> ''' <param name="DatabaseName">der DataBase-Name</param> ''' <returns>Tuple: Item1= Pfad, Item2=Datenbank-Name (mdf)</returns> Public Function GetDatabaseFilePath(serverName As String, DatabaseName As String) _ As Tuple(Of String, String) Dim temp As Tuple(Of String, String) Dim connectionString As String _ = "Data Source=" + serverName + ";Initial Catalog=master;Integrated Security=True" Dim filePath As String = "" ' sys.master_files enthält Informationen zu allen Datenbankdateien Dim query As String = "SELECT physical_name FROM sys.master_files" _ + " WHERE database_id = DB_ID('" & DatabaseName & "') AND type_desc = 'ROWS'" Using connection As New SqlConnection(connectionString) Using command As New SqlCommand(query, connection) Try connection.Open() ' Die Abfrage gibt den Dateipfad als Zeichenfolge zurück Dim result As Object = command.ExecuteScalar() If result IsNot Nothing Then filePath = result.ToString() End If Catch ex As Exception ' Fehlerbehandlung Debug.Print("Fehler beim Ermitteln des Dateipfads: " & ex.Message) End Try End Using End Using temp = New Tuple(Of String, String)(GetPath(filePath), GetName(filePath)) Return temp End Function
Beispielaufruf:
Dim dbPath As String = GetDatabaseFilePath("DeinServerName", "DeinDatabaseName").Item1 Dim dbName As String= GetDatabaseFilePath("DeinServerName", "DeinDatabaseName").Item2
Und jetzt noch die beiden Hilfsfunktionen:
Public Function GetPath(Full As String) As String For i As Integer = Full.Length - 1 To 0 Step -1 ' Find the rightmost or /, which should be cut off the file part If Full.Substring(i, 1) = "" OrElse Full.Substring(i, 1) = "/" Then Return Full.Substring(0, i) + "" End If Next Return "" End Function
Public Function GetName(Full As String) As String ' If it's has path it gets how long it only the path is Dim Start As Integer = GetPath(Full).Length ' take of the path and the extension Return RemoveExtension(Full.Substring(Start)) End Function


Physischen Namen einer SQL-Datenbank ermitteln