randytan
randytan

Reputation: 1039

Error Getting Index Number on Database Using C#, Showing -1

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.

Upvotes: 0

Views: 272

Answers (2)

Vishal Suthar
Vishal Suthar

Reputation: 17194

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());

Upvotes: 0

John Woo
John Woo

Reputation: 263843

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

identity = Convert.ToInt32(cmd.ExecuteScalar());

Upvotes: 2

Related Questions