我在自动增加字段(ID
)中访问数据库。
我插入这样的记录(在C#中)
SQL = "insert into TermNumTbl (DeviceID,IP) values ('" + DeviceID + "','" + DeviceIP + "') ";
OleDbCommand Cmd = new OleDbCommand(SQL, Conn);
Cmd.ExecuteNonQuery();
Cmd.Dispose();
Conn.Close();
如何获取最后一个插入号码?
我不想运行新查询我知道在sql中有类似SELECT @@IDENTITY
但我不知道如何使用它
提前致谢
答案 0 :(得分:14)
有关此内容的更多信息:Getting the identity of the most recently added record
Jet 4.0提供程序支持@@Identity
string query = "Insert Into Categories (CategoryName) Values (?)";
string query2 = "Select @@Identity";
int ID;
string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb";
using (OleDbConnection conn = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("", Category.Text);
conn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = query2;
ID = (int)cmd.ExecuteScalar();
}
}
答案 1 :(得分:5)
我猜你甚至可以为OleDbConnection
...
public static int GetLatestAutonumber(
this OleDbConnection connection)
{
using (OleDbCommand command = new OleDbCommand("SELECT @@IDENTITY;", connection))
{
return (int)command.ExecuteScalar();
}
}
答案 2 :(得分:0)
我更喜欢指出命令的类型 与Pranay Rana提供的良好解决方案非常相似
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql_Insert;
cmd.ExecuteNonQuery();
cmd.CommandText = sql_obtainID;
resultado = (int)comando.ExecuteScalar();
}
答案 3 :(得分:0)
query = "Insert Into jobs (jobname,daterecieved,custid) Values ('" & ProjectNAme & "','" & FormatDateTime(Now, DateFormat.ShortDate) & "'," & Me.CustomerID.EditValue & ");"'Select Scope_Identity()"
' Using cn As New SqlConnection(connect)
Using cmd As New OleDb.OleDbCommand(query, cnPTA)
cmd.Parameters.AddWithValue("@CategoryName", OleDb.OleDbType.Integer)
If cnPTA.State = ConnectionState.Closed Then cnPTA.Open()
ID = cmd.ExecuteNonQuery
End Using
答案 4 :(得分:0)
使用@ Lee.J.Baxter的方法(这很好,因为其他人不适合我!)我逃脱了扩展方法,只是在表单内部添加内联:
OleDbConnection con = new OleDbConnection(string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='{0}'", DBPath));
OleDbCommand cmd = con.CreateCommand();
con.Open();
cmd.CommandText = string.Format("INSERT INTO Tasks (TaskName, Task, CreatedBy, CreatedByEmail, CreatedDate, EmailTo, EmailCC) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}')", subject, ConvertHtmlToRtf(htmlBody), fromName, fromEmail, sentOn, emailTo, emailCC);
cmd.Connection = con;
cmd.ExecuteScalar();
using (OleDbCommand command = new OleDbCommand("SELECT @@IDENTITY;", con))
{
ReturnIDCast =(int)command.ExecuteScalar();
}
注意:在大多数情况下,您应该使用参数而不是我在此处使用的string.Format()方法。我这次只是这样做,因为它更快,我的插入值不是来自用户的输入,所以它应该是安全的。
答案 5 :(得分:-2)
简单,
我们在excel中如何复制上面单元格中的文本?
是的,只是 ctrl+" 组合, 是的,它也适用于 MS ACCESS。
您可以使用上面的按键组合复制上面的记录字段文本,只需确保在移动下一个字段之前是否应用了重复验证或编辑了字段数据。
如果您需要更多验证或任何特别之处,请继续搜索堆栈溢出。