如何获得插入数据库中的最后一个值以生成新值

本文关键字:新值 最后一个 何获得 插入 数据库 | 更新日期: 2023-09-27 17:50:56

使用文本区,我通过点击按钮发送值到数据库,但我想要postID自动生成我怎么能做到这一点?

protected void btnPost_Click(object sender, EventArgs e)
{
    string PostQuery = "INSERT INTO [Post] (PostID,PostDet,Votes,UserID) VALUES('<auto Genatare post ID>','" + TxtPost.Text + "','12','Us001')";
    dbClass.ConnectDataBaseToInsert(PostQuery);
    Response.Redirect("~/computing.aspx");
}

如何获得插入数据库中的最后一个值以生成新值

您可以使PostID成为UNIQUEIDENTIFIER列,然后传入新生成的GUID (Guid.NewGuid())。

另外,请使用参数化查询来避免SQL注入。特别是当输入直接来自WEB用户时。

为此,更改您的ConnectDataBaseToInsert方法,使其不接受SQL文本,而是使用您准备的具有相应参数的SqlCommand


从你的评论到问题:postd应该像PO0001。那么,正确执行并尊重并发性的唯一方法是生成一个存储过程,该存储过程接受要插入的值,从而生成ID本身。

为此,创建一个包含最后一个post ID的新表。然后,使用UPDATE ... OUTPUT语句一次递增并返回。这是对post ID进行原子更新的唯一方法,这样就不会有两个用户创建相同的ID。

示例表postdtable

Current
=======
0

示例SELECT更新和检索当前post ID:

-- We need a temp table, because OUTPUT can not output into a single variable
-- This increments Current by one and outputs the value that was set in one go.
-- This prevents simultaneous calls to get the same ID
DECLARE #postID (ID INT)
UPDATE PostIDTable
OUPUT INSERTED.Current INTO #postID
SET
    Current = Current + 1
-- Get the value from the temp table and convert it into the desired format
DECLARE @pID INT = (SELECT TOP 1 ID FROM #postID)
DECLARE @id NVARCHAR(6) = 'PO' + RIGHT('0000' + CONVERT(NVARCHAR, @pID), 4)
-- Do the actual INSERT
INSERT INTO (PostDet, Votes,UserID) VALUES (@id, ..., ...)

应该将PostID列设置为IDENTITY(1,1)列(在使用MSSQL的情况下)。服务器)。因此,当您向数据库插入新行时,相应的PostID值将由数据库自动生成。对于您可能使用的其他RDBMS也是如此。

完成上述更改后,您的代码将更改为以下内容:

protected void btnPost_Click(object sender, EventArgs e)
{
    string PostQuery = "INSERT INTO [Post] (PostDet,Votes,UserID) VALUES("TxtPost.Text + "','12','Us001')";
    dbClass.ConnectDataBaseToInsert(PostQuery);
    Response.Redirect("~/computing.aspx");
}

如果PostId是自动生成的,只需要这样做:

protected void btnPost_Click(object sender, EventArgs e)
{
    string PostQuery = "INSERT INTO [Post] (PostDet,Votes,UserID) VALUES('" + TxtPost.Text + "','12','Us001')";
    dbClass.ConnectDataBaseToInsert(PostQuery);
    Response.Redirect("~/computing.aspx");
}

从查询中删除PostId,它将生成下一个Id

最好的方法是为您的表使用自动增量列ID。请参阅w3school教程,其中描述了所有主数据库的构造。

试试这个…

select * from tablename order by id desc limit 1

其中id为主键属性名