Sqlce extraire les données d'une base au format texte

Contenu du snippet

Ces quelques lignes permettent d'extraire les données d'une base de donnée
Le fichier Requete.txt doit-être dans le même répertoire que l'appli

Source / Exemple :


Imports System.IO
Imports System.Text
Imports System.Data.SqlServerCe
Module Data
#Region "Declarations"
    Public CheminCourant As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly.GetName.CodeBase)
    Public Const ListeSeparation = ";"
#End Region
    Public Sub ShowErrors(ByVal e As SqlCeException)
        Dim errorCollection As SqlCeErrorCollection = e.Errors

        Dim bld As New StringBuilder
        Dim inner As Exception = e.InnerException

        If Not inner Is Nothing Then
            MessageBox.Show(("Inner Exception: " & inner.ToString()))
        End If

        Dim err As SqlCeError

        ' Enumerate each error to a message box.
        For Each err In errorCollection
            bld.Append((ControlChars.Cr & " Error Code: " & err.HResult.ToString("X")))
            bld.Append((ControlChars.Cr & " Message   : " & err.Message))
            bld.Append((ControlChars.Cr & " Minor Err.: " & err.NativeError))
            bld.Append((ControlChars.Cr & " Source    : " & err.Source))

            ' Retrieve the error parameter numbers for each error.
            Dim numPar As Integer
            For Each numPar In err.NumericErrorParameters
                If 0 <> numPar Then
                    bld.Append((ControlChars.Cr & " Num. Par. : " & numPar))
                End If
            Next numPar

            ' Retrieve the error parameters for each error.
            Dim errPar As String
            For Each errPar In err.ErrorParameters
                If [String].Empty <> errPar Then
                    bld.Append((ControlChars.Cr & " Err. Par. : " & errPar))
                End If
            Next errPar

            MessageBox.Show(bld.ToString())
            bld.Remove(0, bld.Length)
        Next err
    End Sub
    Public Sub LireRequete()
        Dim Sr As New StreamReader(CheminCourant & "\Requete.txt")
        Dim StrInput, NomFichier, Requete, NomBase, Nombre As String
        Try
            NomBase = StrInput
            Requete = Sr.ReadLine
            Nombre = Sr.ReadLine
            NomFichier = Sr.ReadLine
            MsgBox("Requete " & Requete & "(" & CStr(Nombre) & ") sur " & NomBase & " pour " & NomFichier)
            ExtractData(NomBase, Nombre, Requete, NomFichier)
            Sr.Close()
        Catch ex As Exception
            ShowErrors(ex)
        End Try
    End Sub
    Public Sub ExtractData(ByVal NomBase As String, ByVal Nombre As String, ByVal Requete As String, ByVal NomFichier As String)
        Dim maconnexion As SqlCeConnection = Nothing
        Dim Detail() As String
        Dim Sw As New StreamWriter(CheminCourant & NomFichier, True)
        Dim I, Compteur, Etat As Integer
        Dim Tampon As String
        Detail = Nombre.Split(ListeSeparation)
        I = 0
        Try
            maconnexion = New SqlCeConnection(("Data Source=" & CheminCourant & NomBase))
            maconnexion.Open()
            Dim mycmd As SqlCeCommand
            Dim MonResultat As SqlCeDataReader
            mycmd = maconnexion.CreateCommand
            mycmd.CommandText = Requete
            MonResultat = mycmd.ExecuteReader
            While MonResultat.Read()
                If Detail(1) = "str" Then Tampon = MonResultat.GetString(I)
                If Detail(1) = "int" Then Tampon = CStr(MonResultat.GetInt16(I))
                If CInt(Detail(0)) > 0 Then
                    For I = 1 To CInt(Detail(0))
                        Tampon = Tampon & ListeSeparation
                        If Detail(I + 1) = "str" Then Tampon = Tampon & MonResultat.GetString(I)
                        If Detail(I + 1) = "int" Then Tampon = Tampon & CStr(MonResultat.GetInt16(I))
                    Next
                End If
                Sw.WriteLine(Tampon)
                Tampon = ""
                I = 0
                Compteur += 1
            End While
            Sw.Flush()
            Sw.Close()
            maconnexion.Dispose()
            maconnexion.Close()
            MsgBox(Compteur & " enregistrements exportés dans " & NomFichier)
        Catch ex As Exception
            MsgBox(ex.Message & "-" & CStr(Compteur), MsgBoxStyle.Exclamation)
            ShowErrors(ex)
        End Try
    End Sub
End Module

Conclusion :


exemple d'un fichier Requete.txt
\My Documents\MaBase.sdf
SELECT Nom, Prenom, Points FROM Score
4;str;str;int
\Score.csv

Il est très pratique d'utiliser query analyser pour naviguer dans les base et connaître le nom des champs

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.