简体   繁体   English

使用C#获取数据库索引号时出错,显示-1

[英]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. 我在C#中创建了一个脚本,使用ComboBox上的someparameter获取数据库上的索引号。

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. “好莱坞电影” - > ID:2(在DB中)上面脚本的结果是-1。

How to solve that? 怎么解决? thanks in advance. 提前致谢。

use ExecuteScalar() if you want to fetch single value. 如果要获取单个值,请使用ExecuteScalar()

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

ExecuteNonQuery will returns the number of rows affected. ExecuteNonQuery将返回受影响的行数。

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 因此,您需要使用ExecuteScalar ,它返回查询返回的结果集中第一行的第一列

"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." “对于UPDATE,INSERT和DELETE语句,返回值是受命令影响的行数。对于所有其他类型的语句, 返回值为-1 。如果发生回滚,则返回值也为-1。 “

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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