如何在JDBC中启动事务?
事务是在数据库上执行的一组工作单元。事务是按逻辑顺序完成的工作单元或序列,无论是由用户手动执行还是由某种数据库程序自动执行。
事务是对数据库进行的一个或多个更改的传播。例如,如果您正在创建记录、更新记录或从表中删除记录,那么您就是在对该表执行事务。控制这些事务以确保数据完整性和处理数据库错误非常重要。
结束事务
执行完所需的操作后,可以使用commit命令结束/保存事务。在JDBC应用程序中,可以使用**Connection**接口的**commit()**方法来实现。
每当事务中出现问题时,您可以使用回滚来撤消对数据库所做的更改。
启动事务
通常,在JDBC中,建立连接后,默认情况下,您的连接将处于自动提交模式,即使用此连接执行的每个语句都会自动保存,这意味着数据库管理其自身的事务,并且每个单独的SQL语句都被视为一个事务。
您可以通过关闭自动提交模式来启用手动事务支持。为此,您需要将布尔值false传递给**Connection**接口的**setAutoCommit()**方法。
conn.setAutoCommit(false);
示例
以下程序使用批处理将数据插入此表中。在这里,我们将自动提交设置为false,将所需的语句添加到批处理中,执行批处理,然后自行提交数据库。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class BatchProcessing_Statement {
public static void main(String args[])throws Exception {
//Getting the connection
String mysqlUrl = "jdbc:mysql:///sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Creating a Statement object
Statement stmt = con.createStatement();
//Setting auto-commit false
con.setAutoCommit(false);
//Statements to insert records
String insert1 = "INSERT INTO Dispatches( Product_Name , Name_Of_Customer , "
+ "Month_Of_Dispatch , Price, Location) VALUES "
+ "('KeyBoard', 'Amith', 'January', 1000, 'hyderabad')";
String insert2 = "INSERT INTO Dispatches( Product_Name , Name_Of_Customer , "
+ "Month_Of_Dispatch , Price, Location) VALUES "
+ "('Earphones', 'SUMITH', 'March', 500, 'Vishakhapatnam')";
String insert3 = "INSERT INTO Dispatches( Product_Name , Name_Of_Customer , "
+ "Month_Of_Dispatch , Price, Location) VALUES "
+ "('Mouse', 'Sudha', 'September', 200, 'Vijayawada')";
//Adding the statements to the batch
stmt.addBatch(insert1);
stmt.addBatch(insert2);
stmt.addBatch(insert3);
//Executing the batch
stmt.executeBatch();
//Saving the changes
con.commit();
System.out.println("Records inserted......");
}
}输出
Connection established...... Records inserted......
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP