简体   繁体   中英

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

I want to retrieve the last inserted id in the user_table, but when I try it in the code in Visual Studio, it says that it get nothing from the query.

I tried this code in my webform in Visual Studio 2017. but it can't get the data that I want. When I tried this code in the SQL Server 2014, it shows the data that I want.

//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)
)

Your SQL for creating the table is missing the name of the primary key, "id-user", should look like this:

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

Also, as @hassan.ef pointed out, dr2 needs an index even though you are only selecting one column, so you could use either dr2[0].ToString() or dr2["id_user"].ToString() .

use this one:

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

istead of:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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