开发者

How do I know when a field/row in mysql updated successfully?

Right now开发者_JAVA技巧, I have my database setup so that I insert a new row. But if the row I'm trying to insert is a duplicate (based off of my primary key id), then I increment the count field by 1.

Right now I want to know when I was able to create a new row instead of having it increment count. How would I do this in an efficient/proper manner?

The current method I'm thinking of doing this, is by querying the id first and checking if it exists. But I feel like there's a faster/better way. I've also read about triggers but I've heard that they're bad/risky to use.


Use INSERT ... ON DUPLICATE KEY UPDATE... Then query for affected_rows (as @Tarek Fadel suggested). MySQL will return 1 if the row was inserted, or 2 if existing row were updated.


Use your database AUTO INCREMENT option for your primary ID field. Only propper solution.

Here you have mysql reference, but that exist in just every database engine: http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html


How about an auto_increment on the id column?

Otherwise you might use SELECT MAX(id) FROM TABLE to retreive the highest id and add one to it, but that isn't thread-safe since another user might execute the same insert at the same time. Auto_increment fixes that for you.


PHP's mysql_affected_rows()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜