Quantcast
Channel: Visual Basic Tips and Tricks
Viewing all articles
Browse latest Browse all 2212

Leggere un file di testo e memorizzare i dati in un database

$
0
0

Ho creato un database, all'interno della mia applicazione,  con Microsoft SQL Server Compact 3.5, ora vorrei che questo database venisse aggiornato prelevando i dati da un file di testo; ho scritto il seguente codice:

 

Imports System.Data.SqlServerCe
Public Class Form1
   

    
Private Sub buttonSelezionaFile_Click(sender As System.Object, e As System.EventArgsHandles buttonSelezionaFile.Click
        
Dim cartpregeo As String = "C:\pregeo\Arch\"
        
Dim openFileDialog As New OpenFileDialog()
        openFileDialog.Filter = 
"dat|*.dat"
        openFileDialog.Title = 
"Seleziona l'archivio dei comuni"
        openFileDialog.InitialDirectory = cartpregeo

        
If openFileDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
            TextBox1.Text = openFileDialog.FileName

        
End If
    
End Sub

    
Private Sub buttonAggiorna_Click(sender As System.Object, e As System.EventArgsHandles buttonAggiorna.Click
        
Dim filecomuni As String = TextBox1.Text
        
Dim comune As String = Nothing
        
Dim Regione As String = Nothing
        
Dim siglaprov As String = Nothing
        
Dim codcomune As String = Nothing
        
Dim sezione As String = Nothing
        
Dim rec As Int32 = -1
        
Dim sqlCon As SqlCeConnection = Nothing
        
Dim sSqlCon As String = String.Empty
        
Dim cmdSQL As SqlCeCommand = Nothing
        sSqlCon = 
My.Settings.MyDatabase_1ConnectionString
        sqlCon = 
New SqlCeConnection(sSqlCon)
       



        
If My.Computer.FileSystem.FileExists(Application.StartupPath & "\Comuni.txt"Then
            
My.Computer.FileSystem.DeleteFile(Application.StartupPath & "\Comuni.txt", FileIO.UIOption.AllDialogs, FileIO.RecycleOption.DeletePermanently)
        
End If
        
Using MyReader As New Microsoft.VisualBasic.
                        FileIO.
TextFieldParser(
                          filecomuni)
            MyReader.TextFieldType = FileIO.
FieldType.Delimited
            MyReader.SetDelimiters(
"@")
            
Dim currentRow As String()
            
While Not MyReader.EndOfData
                
Try
                    currentRow = MyReader.ReadFields()
                    
Dim currentField As String
                    
For Each currentField In currentRow
                        rec += 1
                        
If currentField.Substring(0, 1) <> "B" Then Continue For
                        
Dim lun As Int32 = currentField.Length
                        sezione = currentField.Substring(1, 1)
                        
If sezione = " " Then
                            codcomune = currentField.Substring(2, 4)
                        
Else
                            codcomune = currentField.Substring(2, 4) & sezione
                        
End If
                        siglaprov = currentField.Substring(25, 2)
                        Regione = ricercaRegione(siglaprov)

                        
If lun < 67 Then
                            comune = currentField.Substring(29, lun - 33).TrimEnd
                        
Else
                            comune = currentField.Substring(29, 34).TrimEnd
                        
End If
                        comune = StrConv(comune, 
VbStrConv.ProperCase)

                       
Try

                            sqlCon.Open()
                            cmdSQL = 
New SqlCeCommand("INSERT INTO Comuni([ID], [Comune],[Provincia],[Regione],[CodFisco]) VALUES(& rec & comune & siglaprov & Regione & codcomune&nbsp", sqlCon)

                           
sqlCon.Close()
                        
Catch ex As Exception
                            
Throw ex
                        
Finally

                        
End Try

                      


                    
Next

                    FileClose()
                
Catch ex As Microsoft.VisualBasic.
                            FileIO.
MalformedLineException
                    MsgBox(
"Line " & ex.Message &
                    
"is not valid and will be skipped.")
                
End Try
            
End While
        
End Using
    
End Sub
    
Function ricercaRegione(provincia As String)
        
Dim righe() As String = System.IO.File.ReadAllLines(Application.StartupPath & "\Provincie.txt")
        
Dim regione As String = Nothing
        
Dim siglaPr As String = Nothing

        
For Each currentRow In righe
            
Dim Elenco As String() = currentRow.Split(";")
            
If Elenco(2) = provincia Then
                regione = Elenco(3)
                
Exit For
            
End If
        
Next
        
Return regione
    
End Function

  

End Class

La lettura del file di testo funziona perfettamente, ma non riesco ad aggiornare il database con dati letti nel suddetto file.

Qualche suggerimento e aiuto?

Grazie 

Giorgio

 


Viewing all articles
Browse latest Browse all 2212