c# - 如何从 MS Access 数据表中检索自动编号值并将其转换为 int64
问题描述
我想从列名“id”的 MS Access 数据表中检索一个自动数字值,并将其转换为 asp.net 中的 C# 中的 Int64。我该怎么做
解决方案
我们可能需要更多的上下文。
然而:
假设我们有这个标记:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="ID" CssClass="table" >
<Columns>
<asp:TemplateField HeaderText="Get ID" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:Button ID="cmdGetID" runat="server" Text="Show ID" OnClick="cmdGetID_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
然后这段代码填充网格。
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
using (OleDbCommand cmdSQL =
new OleDbCommand("SELECT ID, FirstName, LastName, HotelName, City FROM tblHotels ORDER BY HotelName",
new OleDbConnection(Properties.Settings.Default.AccessDB)))
{
cmdSQL.Connection.Open();
GridView1.DataSource = cmdSQL.ExecuteReader();
GridView1.DataBind();
}
}
好的,我们现在有了这个:
好的,现在我们单击一行时的按钮代码 - 让我们从 Access 获取该 ID。
protected void cmdGetID_Click(object sender, EventArgs e)
{
Button cmdSel = (Button)sender;
GridViewRow gvRow = (GridViewRow)cmdSel.Parent.Parent;
int MyID32 = Convert.ToInt32(gvRow.Cells[1].Text);
Int64 MyID64 = Convert.ToInt64(gvRow.Cells[1].Text);
Debug.WriteLine("ID as Int 32 = " + MyID32);
Debug.WriteLine("ID as Int 64 = " + MyID64);
Int64 MyID64Fromtable = 0;
DataTable rstData = new DataTable();
using (OleDbCommand cmdSQL = new OleDbCommand("SELECT * FROM tblHotels where ID = @ID",
new OleDbConnection(Properties.Settings.Default.AccessDB)))
{
cmdSQL.Connection.Open();
cmdSQL.Parameters.Add("@ID", OleDbType.Integer).Value = MyID32;
rstData.Load(cmdSQL.ExecuteReader());
MyID64Fromtable = Convert.ToInt64(rstData.Rows[0]["ID"]);
}
// at this point, we have a 64 bit var called MyID64FromTable
Debug.Print("64 ID value direct from table = " + MyID64Fromtable.ToString());
}
输出:
ID as Int 32 = 307
ID as Int 64 = 307
64 ID value direct from table = 307
因此,该按钮代码从 Access(从网格)中提取 int32 值。
我们也为了好玩,创建了一个数据表。
用 Access 查询填充它,然后将 int32“ID”值(自动编号)从表中提取到变量中。
那么,真正从数据表中提取的一行?
这条线最像你要找的东西:
Int64 MyID64Fromtable = 0;
MyID64Fromtable = Convert.ToInt64(rstData.Rows[0]["ID"]);
推荐阅读
- android - Room - “预打包的数据库具有无效架构” - 随机要求列为 notNull
- javascript - 如何在 ES6 中绑定对象?
- python - 从可迭代中获取 2 元组的可迭代
- html - 不明白我的图像下的空间,我的 css 中没有什么可以改变它?
- javascript - 如何将 JS SDK 集成到 ReactJS 中?
- amazon-web-services - 如何在 AWS CDK 中检索 SecretsManager 密钥
- hive - 使用 rank() 时未能将窗口调用分解为组
- php - Laravel 迁移已成功迁移,但未在表中创建外键关系
- python - 在 discord.py Python 中更新 guild.members
- mysql - 用之前的值 MYSQL 更新重复的行