MSSQL Query Abfrage in ein File schreiben mit Visual Basic?
Ich benötige Hilfe bei einem Programm.
Ich möchte in Visual Basic eine Query Abfrage machen und das Ergebnis (Richtig gegliedert) in eine .csv Datei schreiben. Die Datenbank habe ich via Visual-Studio eingebunden.
1 Antwort
Um Ihr Abfrageergebnis in eine CSV-Datei zu schreiben, verwenden Sie:
Imports System.IO
Imports System.Data
Imports System.Data.Sql
Using sqlcon As New SqlConnection("Data Source=localhost; Initial Catalog=AdventureWorks; User ID=sa; Password=password;")
sqlcon.Open()
Dim sqlCommand As New SqlCommand
Dim sqlDataReader As SqlDataReader
sqlCommand.Connection = sqlcon
sqlCommand.CommandText = "SELECT TOP 100 ProductName,ListPrice FROM Production.Product WHERE ProductName LIKE '%B' ORDER BY ListPrice DESC"
sqlDataReader = sqlCommand.ExecuteReader()
While sqlDataReader.Read()
Dim productName As String
Dim productPrice As Decimal
productName = sqlDataReader.GetString(0)
productPrice = sqlDataReader.GetDecimal(1)
'write to the file here
WriteToCsvFile(productName, productPrice)
End While
End Using
Um in eine CSV-Datei zu schreiben, verwenden Sie:
Imports System.IO
Imports System.Data
Imports System.Data.Sql
Sub WriteToCsvFile(ByVal productName As String, ByVal productPrice As Decimal)
Using sr As New System.IO.StreamWriter("c:\temp\products.csv", False)
sr.WriteLine(productName & "," & productPrice)
End Using
End Sub