douye6812 2014-12-03 08:33
浏览 68
已采纳

如何为数据库对象分配唯一的ID

In my app, any user can create a post object which contains a title, description, and ID. These post objects are stored in a database within a server. However, I need a way to assign unique ID's to the posts, so I can assign the user to their post (only the ID of a post will be stored in the core data of the poster's phone). Right now I'm using integers as the ID. For example, when a user submits a post, I have it so the database is queried and I find the ID of the last post submitted and then make the ID of the current post being submitted one more than the ID of the last one. Then the post is uploaded to the database. I feel like this is bad practice because if 2 people coincidentally submit their post at the same time, their respective posts could be given the same ID. So, what I'm asking is how should I assign some sort of ID to an object in the database to guarantee it to be unique? Should I assign it in a php script and then somehow return that ID back to Xcode? Sorry, I'm new to this.

  • 写回答

1条回答 默认 最新

  • douweng1935 2014-12-03 08:35
    关注

    You can simply use an auto increment id for your posts, so the database does that job for you.

    CREATE TABLE post(
         id INT NOT NULL AUTO_INCREMENT,
         title VARCHAR(255) NOT NULL,
         description VARCHAR(255),
         PRIMARY KEY (id)
    );
    

    Simply check Auto increment example in the mysql documentation

    after adding data to the table you can fetch the last id of the inserted post with the last_insert_id command.

    so if you use PHP as programming language and you are using mysqli for the database access, you can use mysqli_insert_id to fetch the last id (see the example in the php.net documentation for better understanding)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改