首页 > 代码库 > Access获取新插入数据的自增长主键Id

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

  Access数据库不能用output,自己写类似Oracle的Sequence。

 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 }

 

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