如何将 SQL 查询的结果保存在 C# 的变量中?

How to save the result of a SQL query in a variable in c#?

我想尝试将此查询的结果(我想获取主键的值)保存到 MDB 数据库的 c# 中的一个变量中,但我不知道该怎么做:

SELECT @@identity FROM Table

我试过了,但没用:

int variable;

    variable = cmd.CommandText("SELECT @@IDENTITY FROM TABLE");

PD: 不是所有的代码,我只有这部分有问题。

是完整的代码吗?您刚刚创建了命令对象,但没有打开连接,也没有 运行 命令。

using (SqlConnection conn = new SqlConnection(connString))
{
      SqlCommand cmd = new SqlCommand("SELECT @@IDENTITY FROM TABLE", conn);
        try
        {
            conn.Open();
            newID = (int)cmd.ExecuteScalar();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
 }

您可以使用此代码段:

 SqlCommand command = new SqlCommand(
          "SELECT @@IDENTITY FROM TABLE",
          connection);
        connection.Open();

        SqlDataReader reader = command.ExecuteReader();

        if (reader.HasRows)
        {
            while (reader.Read())
            {
                Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
                    reader.GetString(1));
            }
        }