-1

i'm picking up datas from a mysqldatabase and throwing in variables in a C# application. I'm using this code :

int forcatime;
string comandomedia = "select avg(forca_jogador) from jogadores where nome_time = " + time;

ocon.ConnectionString = con;
MySqlCommand media = new MySqlCommand(comandomedia, ocon);
ocon.Open();
forcatime = Convert.ToInt32(media.ExecuteScalar());
ocon.Close();

After doing this I convert "forcatime" ToString and throw it in a MessageBox.

I'd like to know if there's a way to create a class for this operation because everytime I have to do it I write all the code again and again. Thanks

mattmanser
  • 5,719
  • 3
  • 38
  • 50
  • Put it in a method, put that method in a class? Have you tried anything yet? – DGibbs Feb 11 '13 at 14:23
  • Create a class for your `jogadores` table and all methods you need like `GetForcaTime`, but don't create a class which encapsulates database functionality in general. http://stackoverflow.com/questions/9705637/executereader-requires-an-open-and-available-connection-the-connections-curren/9707060#9707060 – Tim Schmelter Feb 11 '13 at 14:25

3 Answers3

1

Something like...

int result = new DataLayerHelper().RunQuery();
MessageBox.Show(result.ToString());

[...]

public class DataLayerHelper
{
    public DataLayerHelper() { }

    public int RunQuery()
    {
        int forcatime;
        string comandomedia = "select avg(forca_jogador) from jogadores where nome_time = " + time;
        ocon.ConnectionString = con;
        MySqlCommand media = new MySqlCommand(comandomedia, ocon);
        ocon.Open();//consider a using statement
        forcatime = Convert.ToInt32(media.ExecuteScalar());
        ocon.Close();

        return forcatime;
    }
}
P.Brian.Mackey
  • 43,228
  • 68
  • 238
  • 348
0

You don't write a class for this, you write a function for this.

public void Foo(params)  
{
    //your code here
}  

What you would do is place this in a "utility" class that is composed of static functions with a private constructor.

Example:

public class DBUtilities  
{  
       private DBUtilities(){}  
       public static void Foo(params)  
       {  
        int forcatime;
    string comandomedia = "select avg(forca_jogador) from jogadores where nome_time = " + time;
    ocon.ConnectionString = con;
    MySqlCommand media = new MySqlCommand(comandomedia, ocon);
    ocon.Open();
    forcatime = Convert.ToInt32(media.ExecuteScalar());
    ocon.Close();
       }  
}  
Woot4Moo
  • 23,987
  • 16
  • 94
  • 151
0

Classes should be created with the logic they intend to encapsulate in mind.

You need to say what this is doing why you are throwing it to the screen ... etc

Plus you have a possible SQL injection in your code depending on where time is coming from.

P.S. I can't type fast as some people here sorry if this doesn't make sense.

TheKingDave
  • 926
  • 1
  • 8
  • 16