0

i have made a script in C# to get index number on database using someparameter on ComboBox.

private int category(string id) {
        int identity = 0;
        try
        {
            MySqlConnection conn = new MySqlConnection(connection.mysqlconnectionbuilder());
            conn.Open();
            MySqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = "SELECT kategori.no FROM kategori WHERE kategori.kategori = @id";
            cmd.Parameters.AddWithValue("@id", id);
            cmd.CommandType = CommandType.Text;
            identity = cmd.ExecuteNonQuery();
            conn.Close();
        }
        catch (MySqlException msqe)
        {
            Console.Write(msqe.ToString());
        }
        return identity;
    }

I want to get Index number based on name example. "Hollywood Movie" --> ID : 2 (in DB) The result from above script is -1.

How to solve that? thanks in advance.

2 Answers 2

2

use ExecuteScalar() if you want to fetch single value.

identity = Convert.ToInt32(cmd.ExecuteScalar());
Sign up to request clarification or add additional context in comments.

1 Comment

hi @JW thanks for your reply. It's working now. :D cheers and Happy New Year.
0

ExecuteNonQuery will returns the number of rows affected.

It is used for Insert, Update or Delete. It returns an integer specifying the number of rows affected.

So you need to use ExecuteScalar which returns the first column of the first row in the result set returned by the query

"For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1."

identity = Int.Parse(cmd.ExecuteScalar());

1 Comment

thanks for your reply @Vishal. Yes, it's using ExecuteScalar and it's working now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.