简体   繁体   English

如何在 java 中进行这项工作

[英]how can make this work in java

I made a java application that read a text file and store it in a database.The database has 2 tables So in order to store the value of text i created two prepared statement in this order我制作了一个 java 应用程序,它读取一个文本文件并将其存储在数据库中。数据库有 2 个表所以为了存储文本的值,我按此顺序创建了两个准备好的语句

  • code for storing data in table 1表1中存储数据的代码
  • code for storing data in table 2表2中存储数据的代码

And that worked perfectly.这非常有效。 However, when there is a Semantic Errors in the second table, the data in the first are still stored, which is not what i intended to.但是,当第二个表中有语义错误时,第一个表中的数据仍然存储,这不是我想要的。

In a nut shell, if there any semantic error int the second table i want nothing to be stored in the database.在螺母 shell 中,如果第二个表中有任何语义错误,我不想在数据库中存储任何内容。 So how can i do it?那么我该怎么做呢?

It may depend on your database, but you should use a transaction, catch any exceptions and rollback the transaction in the case where the data is bad.它可能取决于您的数据库,但您应该使用事务,捕获任何异常并在数据错误的情况下回滚事务。

This link might help you 此链接可能对您有所帮助

What you want is a transaction in your database, which will allow you to roll back the first insert if something goes wrong with the second one.您需要的是数据库中的事务,如果第二个插入出现问题,这将允许您回滚第一个插入。

You're not specifying which database connection technology you're using, but whichever it is try looking through its documentation for "transaction" support.您没有指定您正在使用哪种数据库连接技术,但无论使用哪种技术,都可以尝试查看其文档以获取“事务”支持。

You need to use a transaction.您需要使用事务。 Set autocommit on the connection to false, execute the 2 statements.将连接上的自动提交设置为 false,执行 2 条语句。 If there is an exception then catch this and rollback the transaction, otherwise commit.如果有异常,则捕获并回滚事务,否则提交。 Thanks谢谢

Verify the inputs before writing them to the database.在将输入写入数据库之前验证输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM