im尝试将数据表导出到vb.net中的.csv文件。Ive编写的代码打开了一个保存文件对话框,并成功保存了.csv文件,但该文件为0字节且不包含任何数据。我正在使用MySQL数据库,数据库名称为“ tickedoff”,而我要导出的表为“ pet”。 如果有人能看到我的代码中的错误并为我提供帮助,将不胜感激。.目前我完全感到沮丧。
此代码在Form1中(按钮单击事件):
Private Sub btnPetInfoExport_Click(sender As Object, e As EventArgs) Handles btnPetInfoExport.Click
Dim saveFileDialog1 = New SaveFileDialog()
Dim statement As String = "SELECT pet.petID, pet.petName, pet.species, pet.breed, " _
& "pet.DOB, pet.gender, pet.weight," _
& "CONCAT(customer.lastName, ', ', customer.firstName) AS Customer " _
& "FROM pet INNER JOIN customer ON pet.customerID = customer.customerID " _
& "ORDER BY pet.petID"
Dim petDataTable As DataTable =
DataAccessLayer.GetPetDataTableForExport(statement)
Dim saveFile As StreamWriter
Dim fileName As String = String.Empty
Dim csvBuilder As New StringBuilder()
For i = 0 To petDataTable.Columns.Count - 1
csvBuilder.Append(petDataTable.Columns(i).ColumnName + ","c)
Next
csvBuilder.Append(vbCr & vbLf)
For i = 0 To petDataTable.Rows.Count - 1
For o = 0 To petDataTable.Columns.Count - 1
csvBuilder.Append(petDataTable.Rows(i)(o).ToString().Replace(",", ";") + ","c)
Next
csvBuilder.Append(vbCr & vbLf)
Next
saveFileDialog1.Filter = "CSV files ( .csv)|.csv|ALL files (.)|. "
If saveFileDialog1.ShowDialog = System.Windows.Forms.DialogResult.OK Then
fileName = saveFileDialog1.FileName
Try
saveFile = File.CreateText(fileName)
Catch ex As Exception
Throw ex
End Try
End If
End Sub
此函数从上面的子函数中调用,并且在一个单独的类中,称为“数据访问层”:
Public Shared Function GetPetDataTableForExport(statement As String) As
DataTable
Dim petDataTableCommand As New MySqlCommand(statement)
Dim petDataTable As New DataTable()
Dim connection As New MySqlConnection("server=localhost; Port=3306; database=tickedoff; username=root;")
Dim petDataTableAdapter As MySqlDataAdapter = New MySqlDataAdapter
petDataTableCommand.CommandType = CommandType.Text
petDataTableCommand.Connection = connection
Try
connection.Open()
petDataTableAdapter.SelectCommand = petDataTableCommand
'fill the table with the pet data from the database
petDataTableAdapter.Fill(petDataTable)
Catch ex As Exception
Throw ex
Finally
connection.Close()
petDataTableAdapter.Dispose()
connection.Dispose()
End Try
Return petDataTable
End Function