mysql - C# access List after return -
i'm noob c# i'm trying create simple code connecting mysql database (most of code got google). have part database selected , stored in list. want access class have no idea how , couldn't find answer on google either (this thread didn't worked me: access list class) can please me?
here's particular code:
public list<string>[] select() { string query = "select * users"; //create list store result list<string>[] list = new list<string>[3]; list[0] = new list<string>(); list[1] = new list<string>(); list[2] = new list<string>(); //open connection if (this.openconnection() == true) { //create command mysqlcommand cmd = new mysqlcommand(query, connection); //create data reader , execute command mysqldatareader datareader = cmd.executereader(); //read data , store them in list while (datareader.read()) { list[0].add(datareader["id"] + ""); list[1].add(datareader["test"] + ""); list[2].add(datareader["balance"] + ""); } //close data reader datareader.close(); //close connection this.closeconnection(); //return list displayed return list; } else { return list; } }
seriously think way you've structured data here, strange.
you're creating array of objects, object list of string:
list<string>[] list = new list<string>[3];
you want thinking in objects; create class represents data; in case user. this:
public class user { public string id { get; set; } public string test { get; set; } public string balance { get; set; } }
so i'd following:
- create class represents each user record.
- create variable hold list of users.
- read mysql , assign each record new user object.
- add user list.
- return list.
change return type of select method list<user>
this:
public list<user> select() {
then amend rest of method create , return list of users.
public list<user> select() { list<user> list = new list<user>(); if (this.openconnection() == true) { mysqlcommand cmd = new mysqlcommand(query, connection); mysqldatareader datareader = cmd.executereader(); while (datareader.read()) { user user = new user(); user.id = datareader["id"].tostring(); user.test = datareader["test"].tostring(); user.balance = datareader["balance"].tostring(); list.add(user); } datareader.close(); this.closeconnection(); } return list; }
then can use list this:
classthatcontainsselectmethod yourdbobject = new classthatcontainsselectmethod(); list<user> users = yourdbobject.select(); foreach (user user in users) { console.writeline(user.id, user.test, user.balance); }
this code of course better structured factories , error/null checks should going in right direction.
Comments
Post a Comment