簡體   English   中英

查詢在Visual Studio 2017中不起作用,但直接在SQL Server中起作用

[英]Query doesn't work in Visual Studio 2017, but works directly in SQL Server

我想檢索user_table中最后插入的id,但是當我在Visual Studio的代碼中嘗試使用它時,它說它從查詢中什么也沒有。

我在Visual Studio 2017的Web窗體中嘗試了此代碼。但是無法獲取所需的數據。 當我在SQL Server 2014中嘗試此代碼時,它顯示了所需的數據。

//This is the code in visual studio
string tklastid = "SELECT TOP 1 id_user FROM user_table ORDER BY id_user DESC".ToString();
    SqlCommand lastid = new SqlCommand(tklastid, con);
    SqlDataReader dr2;
    dr2 = lastid.ExecuteReader();
    try
    {
        while (dr2.Read())
        {
            Label1.Text = dr2.ToString();
            userlast = dr2.ToString();
        }
    }
    catch (Exception exe)
    {
        Label1.Text = exe.Message;
    }
    dr2.Close();
    con.Close();

//this is the code when I make the table
create table user_table
(
    int identity(1,1) primary key,
    user_email varchar(50) not null,
    user_name varchar(50)
)

用於創建表的SQL缺少主鍵名稱“ id-user”,應如下所示:

   create table user_table
   (
       id_user int identity(1,1) primary key,
       user_email varchar(50) not null,
       user_name varchar(50)
   )

另外,正如@ hassan.ef所指出的,即使您僅選擇一列, dr2需要一個索引,因此您可以使用dr2[0].ToString()dr2["id_user"].ToString()

使用這個:

  Label1.Text = dr2["id_user"].ToString();
  userlast = dr2["id_user"].ToString();

代替:

    Label1.Text= dr2.ToString();
    userlast = dr2.ToString();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM