[MY-RS] Probleme Base de Donnée

Pour les scripts écrits en C#
Règles du forum
Merci de respecter la NOMENCLATURE suivante pour vos TITRES de messages :

Commencez par le niveau de vos scripts
DB = Débutant
MY = Moyen
CF = Confirmé

Puis le domaine d'application
-RS = Réseau
-AL = Algorithmie

Exemple :

[DB-RS] Mouvement perso multijoueur
Lamarche
Messages : 5
Inscription : 12 Oct 2017 18:04

[MY-RS] Probleme Base de Donnée

Message par Lamarche » 12 Oct 2017 18:19

Bonjour tout le monde
j'ai actuellement un script pour me connecter à ma bdd et pour agir sur mon champs points voir photo ci dessous seul probleme dans ma scene j'ai 2 boutons le premier sert a me rajouter 10 points et le second me sert a synchroniser mes points entre le jeu et ma bdd
le probleme cest que je le fais 1 fois tous marche j'ai bien la synchronisation qui marche mais si je veux le faire une 2e fois j'ai cette erreur que je n'arrive pas à corriger :

MySql.Data.MySqlClient.MySqlException: There is already an open DataReader associated with this Connection which must be closed first.

voila mon code si une âme bien aimable aurai la gentillesse de bien vouloir m'aider ça serai extrêmement appréciable

Code : Tout sélectionner

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using MySql.Data.MySqlClient;
using System;
using UnityEngine.UI;
using System.Text.RegularExpressions;
using UnityEngine.SceneManagement;

public class sqlManager : MonoBehaviour
{
    public static sqlManager instance;
    [Header("DATABASE")]
    public string host;
    public string database, username, password;
    [Header("REGISTER")]
    public Canvas Canvasregister;
    public InputField RPseudo;
    public InputField RPassword, Rnom, Rprenom, REmail;
    public Text Rtxtinfos;
    MySqlConnection con;
    [Header("Login")]
    public Canvas canvaslogin;
    public InputField Lpseudo;
    public InputField Lpassword;
    public Text Ltxtinfo;
    [Header("info User")]
    public string IPseudo;
    public string INom, Iprenom, IEmail;
    public int IPoints;



    void Start ()
    {
        connectbdd();
    }

    void Awake ()
    {
        if (instance != null)
        {
            Destroy(gameObject);
        }
        else
        {
            instance = this;
            DontDestroyOnLoad(gameObject);

           
        }
    }
void connectbdd()
    {
      
      string cmd = "SERVER=" + host + ";" + "database =" + database + ";User ID=" + username + ";Password=" + password + ";Pooling=true;Charset=utf8";

        try
        {
            con = new MySqlConnection(cmd);
            con.Open();
        }
    
        catch (Exception ex)
        {
            Debug.Log(ex.ToString());
        }

    }

    void Update()
    {
        Debug.Log(con.State);
    }

    bool IsValidLenght(string InputString, int LenghtString)
    {
        if(InputString.Length>LenghtString)
        {
            return true;
        }else
        {
            return false;
        }
    }

    bool Isvalidemail(string InputEmail)
    {
        Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
        Match match = regex.Match(InputEmail);
        if (match.Success)
        {
            return true;

       }
        else
        {
            return false;
        }
    }


    bool Isvalid()
    {
        ColorBlock cbEmail = REmail.colors;

       if (!Isvalidemail(REmail.text))
        {
            Rtxtinfos.text = "Invalid Email";
            cbEmail.normalColor = Color.red;
            REmail.colors = cbEmail;
            return false;
        }
       else
        {
            Rtxtinfos.text = "";
            cbEmail.normalColor = Color.white;
            REmail.colors = cbEmail;
        }

        //Pseudo 
        ColorBlock cbPseudo = RPseudo.colors;
        if(!IsValidLenght(RPseudo.text,4))
        {
            cbPseudo.normalColor = Color.red;
            Rtxtinfos.text = "Pseudo invalid";
            RPseudo.colors = cbPseudo;
            return false;
        }
        else
        {
            cbPseudo.normalColor = Color.white;
            Rtxtinfos.text = "";
            RPseudo.colors = cbPseudo;
        }


        //password
        ColorBlock cbPassword = RPassword.colors;
        if (!IsValidLenght(RPassword.text, 4))
        {
            cbPassword.normalColor = Color.red;
            Rtxtinfos.text = "Password invalid";
            RPassword.colors = cbPassword;
            return false;
        }
        else
        {
            cbPassword.normalColor = Color.white;
            Rtxtinfos.text = "";
            RPassword.colors = cbPseudo;
        }

        //other


        if(!IsValidLenght(Rnom.text,0) || !IsValidLenght(Rprenom.text,0))
        {
            Rtxtinfos.text = "Empty not autorized";
            return false;


        }
        //verification existance peseudo bdd

        try
        {
            connectbdd();
            MySqlCommand Cmdsql = new MySqlCommand("SELECT * FROM `utilisateurs` WHERE `pseudo`='" + RPseudo.text + "'",con);
            MySqlDataReader MyReader = Cmdsql.ExecuteReader();
            string data = null;

            while(MyReader.Read())
            {
                data = MyReader["password"].ToString();
                if(data !=null)
                {
                    Rtxtinfos.text = "Pseudo Exist";
                    MyReader.Close();
                    return false;
                }
            }
            MyReader.Close();
        }
        catch(Exception ex) { Debug.Log(ex.ToString()); }



        Rtxtinfos.text = null;
        return true;
    }



    public void Register ()
    {
        if(Isvalid())
        {
            
            string cmd= "INSERT INTO `game`.`utilisateurs` (`id`, `pseudo`, `password`, `nom`, `prenom`, `email`, `points`) VALUES(NULL, '"+RPseudo.text +"', '"+Md5Sum(RPassword.text)+"', '"+Rnom.text+"', '"+Rprenom.text+"', '"+REmail.text+"', '0')";
            MySqlCommand cmdsql = new MySqlCommand(cmd, con);

            try
            {
                cmdsql.ExecuteReader();
                Rtxtinfos.text = "Register Succesfull";
  
            }

            catch (Exception ex)
            {
                Rtxtinfos.text = ex.ToString();
            }



        }
        else
        {
            Debug.Log("non valid");
        }
    }
     string Md5Sum(string strToEncrypt)
    {
        System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding();
        byte[] bytes = ue.GetBytes(strToEncrypt);

        // encrypt bytes
        System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
        byte[] hashBytes = md5.ComputeHash(bytes);

        // Convert the encrypted bytes back to a string (base 16)
        string hashString = "";

        for (int i = 0; i < hashBytes.Length; i++)
        {
            hashString += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
        }
        
        return hashString.PadLeft(32, '0');
    }
    public void Login()
    {
        try
        {
            connectbdd();
            MySqlCommand Cmdsql = new MySqlCommand("SELECT * FROM `utilisateurs` WHERE `pseudo`='" + Lpseudo.text + "'", con);
            MySqlDataReader MyReader = Cmdsql.ExecuteReader();
            string data = null;

            while (MyReader.Read())
            {
                data = MyReader["password"].ToString();

                if (data == Md5Sum(Lpassword.text))
                {
                    
                    Ltxtinfo.text = "Login Succesfull";
                    //recuperation données utilisateurs
                    Iprenom = MyReader["prenom"].ToString();
                    INom= MyReader["nom"].ToString();
                    IEmail = MyReader["email"].ToString();
                    IPseudo = MyReader["pseudo"].ToString();
                    IPoints =(int)MyReader["points"];
                    SceneManager.LoadScene("menu");
                }
                else
                {
                    Ltxtinfo.text = "Wrong Login or Password";
                }
            }
            if(data==null)
            {
                Ltxtinfo.text = "Account not existing ! ";
            }

            MyReader.Close();
        }
        catch (Exception ex) { Debug.Log(ex.ToString()); }
    }
    public void  ShowRegister ()
    {
        canvaslogin.gameObject.SetActive(false);
        Canvasregister.gameObject.SetActive(true);
    }

    public void Showlogin()
    {
        canvaslogin.gameObject.SetActive(true);
        Canvasregister.gameObject.SetActive(false);
    }

    public void SavePoints()
    {
        string cmd = "UPDATE `utilisateurs` SET `points`=" +IPoints+ " WHERE `pseudo`='" + IPseudo + "'";
        MySqlCommand Cmdsql = new MySqlCommand(cmd, con);
        try
        {

            Cmdsql.ExecuteReader();
            Debug.Log("Update Succesfull");
            
        }
        catch (Exception Ex)
        {
            Debug.Log(Ex.ToString());
            

        }
    }
    }



merciii encore :super:
.
 ! Message de : Max
Utilisez les balises codes. Merci
En cas de doute, lire la Netiquette.

Lamarche
Messages : 5
Inscription : 12 Oct 2017 18:04

Re: [MY-RS] Probleme Base de Donnée

Message par Lamarche » 12 Oct 2017 19:47

Photo de ma bdd:
Image

Avatar de l’utilisateur
boubouk50
ModoGenereux
ModoGenereux
Messages : 6220
Inscription : 28 Avr 2014 11:57
Localisation : Saint-Didier-en-Bresse (71)

Re: [MY-RS] Probleme Base de Donnée

Message par boubouk50 » 13 Oct 2017 09:21

Salut,
MySql.Data.MySqlClient.MySqlException: There is already an open DataReader associated with this Connection which must be closed first.
Comme pour toute lecture/écriture dans des fichiers, les streams doivent être fermés avant d'être ouvert de nouveau

Je n'y connais rien mais je suppose que c'est la variable MyReader qui ne se ferme pas. Tu as bien un Close () mais il ne doit pas être effectif avant d'appuyer de nouveau. Pourtant ils sont bien dans Try Catch ça ne devrait lever qu'une exception pas planter le programme...
As-tu la ligne incriminée?
"Ce n'est pas en améliorant la bougie, que l'on a inventé l'ampoule, c'est en marchant longtemps."
Nétiquette du forum
Savoir faire une recherche
Apprendre la programmation

Lamarche
Messages : 5
Inscription : 12 Oct 2017 18:04

Re: [MY-RS] Probleme Base de Donnée

Message par Lamarche » 13 Oct 2017 10:57

Pense tu il ne me retourne pas la ligne sinon ça serait trop simple .... :pleur4:

Farstone
Messages : 187
Inscription : 04 Déc 2016 09:38

Re: [MY-RS] Probleme Base de Donnée

Message par Farstone » 13 Oct 2017 11:44

Fait un autre bouton qui close le stream pour voir, je pense que ton while empêche l’exécution du close car il est actif tant que le stream est open. A part ça comment tu compte éviter quelqu'un de récupérer les info de ta db si c'est stocker côté client ?

Avatar de l’utilisateur
boubouk50
ModoGenereux
ModoGenereux
Messages : 6220
Inscription : 28 Avr 2014 11:57
Localisation : Saint-Didier-en-Bresse (71)

Re: [MY-RS] Probleme Base de Donnée

Message par boubouk50 » 13 Oct 2017 11:49

De ce que j'ai lu tu ne peux avoir qu'un seul DataReader en même temps. Dans ton code, je vois plusieurs possibilités d'accès (j'ai survolé hein...), vérifie donc s'il est possible qu'un conflit apparaisse. (Parce que tu utilises un While, ça boucle en laissant l'accès ouvert, il ne faut donc pas que tu ouvres un autre accès pendant cette boucle).
Note that while a DataReader is open, the Connection is in use exclusively by that DataReader. You cannot execute any commands for the Connection, including creating another DataReader, until the original DataReader is closed.
"Ce n'est pas en améliorant la bougie, que l'on a inventé l'ampoule, c'est en marchant longtemps."
Nétiquette du forum
Savoir faire une recherche
Apprendre la programmation

Lamarche
Messages : 5
Inscription : 12 Oct 2017 18:04

Re: [MY-RS] Probleme Base de Donnée

Message par Lamarche » 13 Oct 2017 16:04

Twiixy a écrit :
13 Oct 2017 11:44
Fait un autre bouton qui close le stream pour voir, je pense que ton while empêche l’exécution du close car il est actif tant que le stream est open. A part ça comment tu compte éviter quelqu'un de récupérer les info de ta db si c'est stocker côté client ?
Ma bdd n'est pas stocker sur le client mais sur une rapsberry en local pour le moment ;)

Lamarche
Messages : 5
Inscription : 12 Oct 2017 18:04

Re: [MY-RS] Probleme Base de Donnée

Message par Lamarche » 13 Oct 2017 16:05

boubouk50 a écrit :
13 Oct 2017 11:49
De ce que j'ai lu tu ne peux avoir qu'un seul DataReader en même temps. Dans ton code, je vois plusieurs possibilités d'accès (j'ai survolé hein...), vérifie donc s'il est possible qu'un conflit apparaisse. (Parce que tu utilises un While, ça boucle en laissant l'accès ouvert, il ne faut donc pas que tu ouvres un autre accès pendant cette boucle).
Note that while a DataReader is open, the Connection is in use exclusively by that DataReader. You cannot execute any commands for the Connection, including creating another DataReader, until the original DataReader is closed.
Super merci je vais regarder tous cela x)

Répondre

Revenir vers « (C#) CSharp »