【问题标题】:How to retrive last enty in ACCESS database using C# via OleDB with sql commands如何使用 C# 通过 OleDB 和 sql 命令检索 ACCESS 数据库中的最后一个条目
【发布时间】:2012-03-07 23:42:53
【问题描述】:

Again me with me form 基本程序(使用 Visual C# 2010) 在让我的大部分程序正常工作后,我开始添加一些小的“附加功能”

问题来了:当我添加一个新项目时,我想打开一个MessageBox并写下新项目的id。

表 = 项目,字段 = item_id

尝试使用:

cmd.CommandText = "SELECT LAST(item_id) FROM Item";
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
    id = dr["item_id"].ToString();
}

这是完整的功能:

public void ItemInsert(string name,string creator,string publishing,string itemType,string genere, string year)
{
    string id ="";
    cmd.CommandText = "INSERT INTO Item  (item_name, creator_name,publishing_name,item_type,genre,year_publication,location) VALUES (@item_name, @creator_name,@publishing_name,@item_type,@genre,@year_publication,@location);";
    cmd.Parameters.AddWithValue("@item_name", name);
    cmd.Parameters.AddWithValue("@creator_name", creator);
    cmd.Parameters.AddWithValue("@publishing_name",publishing);
    cmd.Parameters.AddWithValue("@item_type", itemType);
    cmd.Parameters.AddWithValue("@genre",genere);
    cmd.Parameters.AddWithValue("@year_publication",year);
    cmd.Parameters.AddWithValue("@location", 0);//location=0 when in library

    con.Open(); // open the connection
    cmd.ExecuteNonQuery();
    //get item id
    cmd.CommandText = "SELECT LAST(item_id) FROM Item";
    OleDbDataReader dr = cmd.ExecuteReader();
    while (dr.Read())
    {
        id = dr["item_id"].ToString();
    }

    con.Close();
    MessageBox.Show("Item ID : " + id+"","Added new item");
}

【问题讨论】:

  • 如何获取我制作的最后一件商品的 id

标签: c# sql ms-access oledb


【解决方案1】:

替换:

cmd.CommandText = "SELECT LAST(item_id) FROM Item";

与:

cmd.CommandText = "SELECT @@IDENTITY";

【讨论】:

  • 试过了...出现错误:id = dr["item_id"].ToString();错误是:indexoutofrangeexception 未处理,item_id
  • dr[0].ToString(); 当然,你也必须有一个自动编号。
【解决方案2】:

在我的情况下,“IDENTITY”的东西不起作用(可能是因为该字段不是 PK 或 AI)。它始终是 id "0"

我使用了这个查询:

cmd.CommandText = "SELECT TOP 1 item_id FROM Item ORDER BY item_id DESC";

注意“TOP 1”等于其他sql-dialect的“LIMIT 1”

简而言之,无需设置更多 cmd 选项:

object scalarInt = new OleDbCommand("SELECT TOP 1 item_id FROM Item ORDER BY item_id DESC", con).ExecuteScalar();
int lastItemId = (int?) scalarInt ?? 0; 

如果还没有条目,最后一行末尾的 0 是默认返回值。您可以使用 1 作为数据库 ID,通常以 1 开头。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-13
    • 2022-10-14
    • 1970-01-01
    相关资源
    最近更新 更多