Sqlce créer une base sans sql server

Contenu du snippet

Voici comment créer une base SQLCe sur un Pocket PC sans SQL Server. On réalise cette base et on la remplie à partir d'un fichier texte

Source / Exemple :


Imports System.IO
Imports System.Data
Imports System.Data.SqlServerCe
Imports System.Text
    Public CheminCourant As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly.GetName.CodeBase)
    Public Const ListeSeparation As String = ","
    Public Const FichierSQL = "\MaBase.sdf"
    Public Const FicGare = "\listeScores.txt"
#Region "Maintenance Base SQL ExistanTe(ou pas)"
    Public Function CréateDB()
        'Cette procédure permet de vérifier l'existence de la base SDF
        'Si elle n'existe pas on la crée
        If Not File.Exists(CheminCourant & FichierSQL) Then
            VerifieDB = False
            MsgBox("tentative de reconstruire les bases de données")
            'On refabrique la base
            If CreateBase() = True Then
                MsgBox("Création de la Base")
            Else
                MsgBox("Impossible de créer la BD")
                Exit Function
            End If
            ChargeBaseScore()
            VerifieDB = True
        Else
            VerifieDB = True
        End If
    End Function
    Public Function CreateBase() As Boolean
        CreateBase = False
        Dim cu_sql As String
        Dim MySqlCeEngine As New SqlCeEngine("Data Source=" & CheminCourant & FichierSQL)
        MySqlCeEngine.CreateDatabase()
        MySqlCeEngine.Dispose()
        Dim maconnexion As SqlCeConnection = Nothing
        Try
            maconnexion = New SqlCeConnection(("Data Source=" & CheminCourant & FichierSQL))
            maconnexion.Open()
            Dim mycmd As SqlCeCommand
            mycmd = maconnexion.CreateCommand
            'Ici implémenter la lecture d'un fichier SQL.
            'Base Score
            cu_sql = "CREATE TABLE Score(Nom ntext,Prenom ntext, Score int)"
            MsgBox(cu_sql)
            mycmd.CommandText = cu_sql
            mycmd.ExecuteNonQuery()
            MsgBox("Creation base Score: Succès")
            maconnexion.Close()
            CreateBase = True
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation)
        End Try
    End Function
    Public Sub ChargeBaseScore()
        MsgBox(" debut chargement gares")
        Cursor.Current = Cursors.WaitCursor
        Dim Req_sql As String
        Dim sr As StreamReader = New StreamReader(CheminCourant & FicGare)
        Dim StrInput As String
        Dim StrData() As String
        Dim maconnexion As SqlCeConnection = Nothing
        Try
            maconnexion = New SqlCeConnection(("Data Source=" & CheminCourant & FichierSQL))
            maconnexion.Open()
            Dim mycmd As SqlCeCommand
            mycmd = maconnexion.CreateCommand
            Do
                StrInput = sr.ReadLine
                If StrInput Is Nothing Then GoTo suite
                StrData = StrInput.Split(ListeSeparation)
                StrData(0) = Replace(StrData(0), "'", "''")
                Req_sql = "INSERT INTO Gare(Nom, Prenom, Score ) VALUES ('" & StrData(0) & "','" & StrData(1) & "'," & StrData(2) & ");"
                mycmd.CommandText = Req_sql
                mycmd.ExecuteNonQuery()
            Loop Until StrInput Is Nothing
suite:
            MsgBox("Fin de Chargement Score")
            sr.Close()
            maconnexion.Dispose()
            maconnexion.Close()
        Catch ex As Exception
            ShowErrors(ex)
            sr.Close()
            maconnexion.Dispose()
            maconnexion.Close()
            'MsgBox(ex.Message, MsgBoxStyle.Exclamation)
        End Try
        Cursor.Current = Cursors.Default
    End Sub
    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
#End Region

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.