简体   繁体   中英

How to return the value of query from function?

I have crated one function to return the result of executed SQL query as follows:

EDITED :

 public int GetChips(int points, string username)
    {
        int chip = 0;
        string getChips = "SELECT  Chips from tbl_UserInfo where UserName =' " + username + " '";
        con = new MySqlConnection(conString);
        con.Open();
        MySqlCommand cmd = new MySqlCommand(getChips, con);
        MySqlDataReader chips = cmd.ExecuteReader();

        while (chips.Read())
        {
            chip = chips.GetInt32(0);
            if (chip > points)
            {
                if (points == 5000)
                {
                    chip = chip - 5000;
                }
                else if (points == 10000)
                {
                    chip = chip - 10000;
                }
            }


        }
        con.Close();

        return chip;
    }

It returns chip's value as 0. This code does not go in 'while' condition.

What can be the problem ?

How can I solve this ?

Well yes... temp is a MySqlDataReader , not an int . You can't assign a MySqlDataReader to a variable of type int .

I suspect you want:

chip = temp.GetInt32(0);

Note that you should use using statements to release all your resources, rather than just closing the connection explicitly. You should also consider what you want to happen if there's more than one result (or no results).

Additionally, your code will fail at execution time at the moment unless the user puts their username in quotes. Don't fix this by adding quotes to the SQL - use parameterized queries instead. Otherwise you're vulnerable to SQL injection attacks . Basically, you should pretty much never build SQL dynamically using values like this - always parameterize them instead.

temp is a MySqlDataReader whereas chip is an int . Of course your can't assign one to the other.

An answer to your edited question:

Are you sure the select statement is returning any values at all? You have a space inside your ' " and " '" so it will look for ' Rohan ' in stead of 'Rohan' . Try

UserName ='" + username + "'"

Or better yet, like Jon suggested, use parameterized queries!

Because your query just returns a value, so you can use this:

chip  = (int)(command.ExecuteScalar() ?? 0);

Have a look at following link for more detail:

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM