我想检索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)
)
答案 0 :(得分:2)
您用于创建表的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()
。
答案 1 :(得分:2)
使用这个:
Label1.Text = dr2["id_user"].ToString();
userlast = dr2["id_user"].ToString();
代替:
Label1.Text= dr2.ToString();
userlast = dr2.ToString();