多用户 JSP/Servlet 站点的 MySQL 表锁定
您好,我正在开发一个站点,其中 JSP/Servlet 在 Tomcat 上运行作为前端,并使用 MySql 数据库作为后端,通过 JDBC 访问。
该网站的许多用户可以同时访问和写入数据库,我的问题是: 我是否需要在代码中每次对数据库进行写/读访问之前显式地获取锁? 或者 Tomcat 会帮我处理这个问题吗?
您对如何最好地实施这一点有什么建议吗?我已经编写了大量 JDBC 代码,但没有使用锁:/
Hi I am developing a site with JSP/Servlets running on Tomcat for the front-end and with a MySql db for the backend which is accessed through JDBC.
Many users of the site can access and write to the database at the same time ,my question is :
Do i need to explicitly take locks before each write/read access to the db in my code?
OR Does Tomcat handle this for me?
Also do you have any suggestions on how best to implement this ? I have written a significant amount of JDBC code already without taking the locks :/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为当你说“锁”时你正在考虑交易。在最低级别,您的数据库服务器已经确保并行读写不会损坏您的表。
但如果要确保表之间的一致性,则需要使用事务。简而言之,交易为您提供的是全有或全无的保证。也就是说,如果您想在一个表中插入一个 Order,并在另一个表中插入相关的 OrderItems,那么您需要保证的是,如果 OrderItems 的插入失败(在步骤 2 中),对 Order 表(步骤 1)所做的更改也会被回滚。这样,您永远不会遇到订单表中的行在订单项目中没有关联行的情况。
当然,这是对交易的非常简化的表示。如果您认真对待数据库编程,您应该阅读更多相关内容。
在 java 中,您通常大致通过以下步骤来执行事务:
autocommit
设置为false
conn.commit()
当所有一起插入/更新完成时conn.rollback()
I think you are thinking about transactions when you say "locks". At the lowest level, your database server already ensure that parallel read writes won't corrupt your tables.
But if you want to ensure consistency across tables, you need to employ transactions. Simply put, what transactions provide you is an all-or-nothing guarantee. That is, if you want to insert a Order in one table and related OrderItems in another table, what you need is an assurance that if insertion of OrderItems fails (in step 2), the changes made to Order tables (step 1) will also get rolled back. This way you'll never end up in a situation where an row in Order table have no associated rows in Order items.
This, off-course, is a very simplified representation of what a transaction is. You should read more about it if you are serious about database programming.
In java, you usually do transactions by roughly with following steps:
autocommit
tofalse
on your jdbc connectionconn.commit()
when all the insert/updates that goes together are doneconn.rollback()