Access获取新插入数据的自增长主键Id

时间:2022-11-30 13:52:12

  sqlserver有output,Oracle有Sequence。Access用下面的方法,注意两次查询用一个connection:

 1 public int InsertEx(User user)
 2 {
 3     int id = -1;
 4 
 5     using (OleDbConnection conn = new OleDbConnection(AccessHelper.connectionString))
 6     {
 7         conn.Open();
 8 
 9         OleDbCommand cmd = new OleDbCommand { Connection = conn, CommandType = CommandType.Text };
10 
11         string commandText =
12             $"insert into tb_user (username,userpassword,insdate,dr) values (@username, @userpwd, Date(), 0)";
13         List<OleDbParameter> paras = new List<OleDbParameter>
14                                      {
15                                          new OleDbParameter("username", user.UserName),
16                                          new OleDbParameter("userpwd", user.UserPassword)
17                                      };
18 
19 
20         cmd.CommandText = commandText;
21         cmd.Parameters.AddRange(paras.ToArray());
22         cmd.ExecuteNonQuery();
23 
24 
25         cmd.CommandText = "select @@identity as id";
26         cmd.Parameters.Clear();
27         id = Convert.ToInt32(cmd.ExecuteScalar());
28     }
29 
30     return id;
31 }