IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C# Discussion :

Xamarin problème ouverture BDD Sqlite


Sujet :

C#

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre confirmé Avatar de Tchicken
    Homme Profil pro
    Responsable d'exploitation informatique
    Inscrit en
    Août 2017
    Messages
    108
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 58
    Localisation : France, Val d'Oise (Île de France)

    Informations professionnelles :
    Activité : Responsable d'exploitation informatique

    Informations forums :
    Inscription : Août 2017
    Messages : 108
    Par défaut Xamarin problème ouverture BDD Sqlite
    Bonjour à tous,

    j'ai suivi un tuto
    très bien fait, j'ai intégré tous cela à mon projet, mais lorsque j'essaie d'ouvrir la BDD, j'ai l'impression qu'il ne la trouve pas !

    Mon Schéma Sqlite avec 2 tables :
    Nom : image_2021-11-01_092022.png
Affichages : 346
Taille : 62,8 Ko
    App.xaml.cs :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    using System.IO;
    using Xamarin.Forms;
    using Xamarin.Essentials;
    using GenTurfEvo.Views;
    using GenTurfEvo.Repositories;
    using System;
     
    namespace GenTurfEvo
    {
        public partial class App : Application
        {
            readonly string dbPath = Path.Combine(FileSystem.AppDataDirectory, "GenTurfEvo.db");
            public static PronoRepository PronoRepository { get; set; }
            public static HippoRepository HippoRepository { get; set; }
            public App()
            {
                InitializeComponent();
                PronoRepository = new PronoRepository(dbPath);
                HippoRepository = new HippoRepository(dbPath);
                MainPage = new MainPage();
            }
            protected override void OnStart()
            {
            }
            protected override void OnSleep()
            {
            }
            protected override void OnResume()
            {
            }
        }
    }
    Déclaration Table :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    using SQLite;
     
    namespace GenTurfEvo.Models
    {
        [Table("Pronostics")]
        public class Pronostics
        {
            [PrimaryKey]
            public string Id { get; set; }
            public string DateCourse { get; internal set; }
            public int NumReunion { get; internal set; }
            public string Hippodrome { get; internal set; }
            public int NumCourse { get; internal set; }
            public int IdCourse { get; internal set; }
            public int AgeMoyen { get; internal set; }
            public int Distance { get; internal set; }
            public int MaBase { get; internal set; }
            public int Ch1 { get; internal set; }
            public int Ch2 { get; internal set; }
            public int Ch3 { get; internal set; }
            public int Ch4 { get; internal set; }
            public int Ch5 { get; internal set; }
            public int PMaBase { get; internal set; }
            public int PCh1 { get; internal set; }
            public int PCh2 { get; internal set; }
            public int PCh3 { get; internal set; }
            public int PCh4 { get; internal set; }
            public int PCh5 { get; internal set; }
            public string FlgFin { get; internal set; }
        }
    }
    dbPath = "/data/user/0/com.companyname.GenTurfEvo/files/GenTurfEvo.db"

    PronoRepository.cs :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    using GenTurfEvo.Models;
    using SQLite;
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
     
    namespace GenTurfEvo.Repositories
    {
        public class PronoRepository
        {
            private readonly SQLiteAsyncConnection connexion;
            public string StatusMessage { get; set; }
            public PronoRepository(string dbPath)
            {
                connexion = new SQLiteAsyncConnection(dbPath);
            }
            public async Task<List<Pronostics>> GetPronosticsAsync()
            {
                try
                {
                    return await connexion.Table<Pronostics>().ToListAsync();
                }
                catch (Exception ex)
                {
                    StatusMessage = $"Impossible de récupérer les pronostics.\n Erreur : {ex.Message}";
                }
                return new List<Pronostics>();
            }
            public async Task AddPronosticsAsync(string dateCourse, int numReunion, string hippodrome, int numCourse, int idCourse, int ageMoyen, int distance,
                int maBase, int ch1, int ch2, int ch3, int ch4, int ch5, int pMaBase, int pCh1, int pCh2, int pCh3, int pCh4, int pCh5, string flgFin)
            {
                int result = 0;
                try
                {
                    result = await connexion.InsertAsync(new Pronostics { 
                        DateCourse = dateCourse,
                        NumReunion = numReunion,
                        Hippodrome = hippodrome,
                        NumCourse = numCourse,
                        IdCourse = idCourse,
                        AgeMoyen = ageMoyen,
                        Distance = distance,
                        MaBase = maBase,
                        Ch1 = ch1,
                        Ch2 = ch2,
                        Ch3 = ch3,
                        Ch4 = ch4,
                        Ch5 = ch5,
                        PMaBase = pMaBase,
                        PCh1 = pCh1,
                        PCh2 = pCh2,
                        PCh3 = pCh3,
                        PCh4 = pCh4,
                        PCh5 = pCh5,
                        FlgFin = flgFin
                    });
                    StatusMessage = $"{result} pronostics ajouté(s) {dateCourse}-{numReunion}-{hippodrome}-{numCourse}.";
                }
                catch (Exception ex)
                {
                    StatusMessage = $"Impossible d'ajouter un pronostic : {dateCourse}-{numReunion}-{hippodrome}-{numCourse}.\n Erreur : {ex.Message}";
                }
            }
        }
    }
    Connnexion :
    Nom : image_2021-11-01_093833.png
Affichages : 319
Taille : 31,4 Ko

    ex :
    Nom : ErrSqlite.jpg
Affichages : 357
Taille : 179,6 Ko

    J'ai placé genturfevo.db à la racine des projets GenTurfEvo et GenTurfEvo.Android avec propriété "Copier dans le répertoire de sortie = Toujours copier"
    Elle apparait bien dans les deux répertoires suivants :
    -GenTurfEvo\GenTurfEvo\bin\Debug
    -GenTurfEvo\GenTurfEvo.Android\bin\Debug

    Ensuite, j'ai déplacé la BDD dans le projet GenTurfEvo.Android sous l'arborescence Asset avec les propriétés suivantes :
    Action de génération : AndroidAsset
    Copier dans le répertoire : Toujours copier

    Mais toujours rien...

    Un autre tuto :https://www.it-swarm-fr.com/fr/andro...in/1042437841/
    M'indique de copier le code suivant pour décompresser la BDD hors de l'apk :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    string dbName = "db.sqlite";
    string dbPath = Path.Combine (Android.OS.Environment.ExternalStorageDirectory.ToString (), dbName);
    // Check if your DB has already been extracted.
    if (!File.Exists(dbPath))
    {
        using (BinaryReader br = new BinaryReader(Android.App.Application.Context.Assets.Open(dbName)))
        {
            using (BinaryWriter bw = new BinaryWriter(new FileStream(dbPath, FileMode.Create)))
            {
                byte[] buffer = new byte[2048];
                int len = 0;
                while ((len = br.Read(buffer, 0, buffer.Length)) > 0)
                {
                    bw.Write (buffer, 0, len);
                }
            }
        }
    }
    Mais je ne sais pas où le placer !

    Merci de votre aide, Tchicken.

  2. #2
    Membre Expert

    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2010
    Messages
    2 067
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Novembre 2010
    Messages : 2 067
    Par défaut
    Hello,

    il est possible que la database n'existe pas ou que le répertoire ne soit pas bon.

    Tu as un tuto chez Microsoft
    https://docs.microsoft.com/en-us/xam...data/databases

    Perso ce que je préfère faire c'est de créer la bdd en code s'il n'existe pas déjà, dans la doc :
    The constants file specifies default SQLiteOpenFlag enum values that are used to initialize the database connection. The SQLiteOpenFlag enum supports these values:

    Create: The connection will automatically create the database file if it doesn't exist.

  3. #3
    Membre confirmé Avatar de Tchicken
    Homme Profil pro
    Responsable d'exploitation informatique
    Inscrit en
    Août 2017
    Messages
    108
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 58
    Localisation : France, Val d'Oise (Île de France)

    Informations professionnelles :
    Activité : Responsable d'exploitation informatique

    Informations forums :
    Inscription : Août 2017
    Messages : 108
    Par défaut
    merci youtpout978,

    ton lien, ne parle pas de la localisation de la BDD, je pense avoir programmé correctement toute la phase de gestion, lorsque je passe en mode Débug, tout se déroule correctement, le problème semble venir uniquement de la localisation de la base.
    Je vais essayer en la créant par le code, mais ce n'est pas vraiment ce que je souhaite pour l'instant, ma BDD à un schémas spécifique, avec des données préchargées, je vais continuer mes recherches sur la localisation ...

  4. #4
    Membre Expert

    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2010
    Messages
    2 067
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Novembre 2010
    Messages : 2 067
    Par défaut
    Dans le tuto Microsoft ils ont pas l'air d'utiliser le même répertoire que toi

    Et sur le tuto spécialement Android c'est aussi un autre folder XD
    https://docs.microsoft.com/en-us/xam...ing-sqlite-orm

    Dans les différents code que j'ai vu en tant qu'embedded ressource pour Android il tape dans ce dossier System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);

  5. #5
    Membre confirmé Avatar de Tchicken
    Homme Profil pro
    Responsable d'exploitation informatique
    Inscrit en
    Août 2017
    Messages
    108
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 58
    Localisation : France, Val d'Oise (Île de France)

    Informations professionnelles :
    Activité : Responsable d'exploitation informatique

    Informations forums :
    Inscription : Août 2017
    Messages : 108
    Par défaut
    J'ai fait pas mal d'erreurs de débutant

    avec
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "GenTurfEvo.db");
    la base de données est bien ouverte :
    Nom : debbugSqlite.png
Affichages : 303
Taille : 89,3 Ko

    Le problème se situe ailleurs, j'ai ajouté dans le code, la création de la table et j'obtiens cette erreur :
    Nom : image_2021-11-03_162157.png
Affichages : 296
Taille : 198,3 Ko
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    System.AggregateException
      Message=One or more errors occurred. (Cannot create a table without columns (does 'GenTurfEvo.Models.Pronostics' have public properties?))
      Source=mscorlib
      Arborescence des appels de procédure*:
      at System.Threading.Tasks.Task.ThrowIfExceptional (System.Boolean includeTaskCanceledExceptions) [0x00011] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs:2027 
      at System.Threading.Tasks.Task.Wait (System.Int32 millisecondsTimeout, System.Threading.CancellationToken cancellationToken) [0x00043] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs:2759 
      at System.Threading.Tasks.Task.Wait () [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs:2625 
      at GenTurfEvo.Repositories.PronoRepository..ctor (System.String dbPath) [0x00015] in C:\NewTurf\XamarinExemple\GenTurfEvo\GenTurfEvo\GenTurfEvo\Repositories\PronoRepository.cs:16 
      at GenTurfEvo.App..ctor () [0x00025] in C:\NewTurf\XamarinExemple\GenTurfEvo\GenTurfEvo\GenTurfEvo\App.xaml.cs:20 
      at GenTurfEvo.Droid.MainActivity.OnCreate (Android.OS.Bundle savedInstanceState) [0x0002f] in C:\NewTurf\XamarinExemple\GenTurfEvo\GenTurfEvo\GenTurfEvo.Android\MainActivity.cs:21 
      at Android.App.Activity.n_OnCreate_Landroid_os_Bundle_ (System.IntPtr jnienv, System.IntPtr native__this, System.IntPtr native_savedInstanceState) [0x00010] in /Users/builder/azdo/_work/1/s/xamarin-android/src/Mono.Android/obj/Release/monoandroid10/android-29/mcw/Android.App.Activity.cs:2704 
      at (wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.7(intptr,intptr,intptr)
    Cannot create a table without columns (does 'GenTurfEvo.Models.Pronostics' have public properties?)

    la class Pronostics est bien public, je ne comprend pas le problème...

  6. #6
    Membre confirmé Avatar de Tchicken
    Homme Profil pro
    Responsable d'exploitation informatique
    Inscrit en
    Août 2017
    Messages
    108
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 58
    Localisation : France, Val d'Oise (Île de France)

    Informations professionnelles :
    Activité : Responsable d'exploitation informatique

    Informations forums :
    Inscription : Août 2017
    Messages : 108
    Par défaut
    Ca progresse...
    j'ai modifié la classe Pronostics en supprimant "internal " sur la partie set et là, miracle la table se créée sans erreur, je récupère une liste vide.
    Cette partie fonctionne, maintenant je veux travailler avec une table déjà alimentée...

Discussions similaires

  1. [Python 3.X] problème date bdd sqlite
    Par aaristocat dans le forum Tkinter
    Réponses: 3
    Dernier message: 20/03/2020, 09h44
  2. Problème de requête BDD SQLite
    Par torres02 dans le forum Android
    Réponses: 4
    Dernier message: 26/04/2015, 23h20
  3. [WM17] Problème avec tables de BDD SQLite
    Par tveniere dans le forum Windev Mobile
    Réponses: 6
    Dernier message: 04/10/2013, 07h22
  4. Réponses: 2
    Dernier message: 04/03/2013, 16h29
  5. Problème BDD SQLite
    Par Karly dans le forum Android
    Réponses: 2
    Dernier message: 18/03/2012, 12h12

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo