Java

Transaction using java mysql

The transaction is a set of Sql statement that can be executed  as a single unit.the transaction is complete only when all the sql statements in a transaction excute successfully.if any one of the sql statement in the transaction fails the entire transaction is rolled back.

paste the code inside the main method

import java.sql.*;

public class Transaction 
{
 public static void main(String args[])
 {
  Connection con;
  PreparedStatement ps1;
   try {
   Class.forName("com.mysql.jdbc.Driver");
   con = DriverManager.getConnection("jdbc:mysql://localhost/vmproducts","root","");
    
    con.setAutoCommit(false);
    
    ps1 = con.prepareStatement("insert into product(pname,price,qty)values(?,?,?)");
    ps1.setString(1,"Mouse");
    ps1.setInt(2,15000);
    ps1.setInt(3,100);
    int first = ps1.executeUpdate();
    System.out.println("First Row Inserted but not commited");
    
    ps1 = con.prepareStatement("insert into product(pname,price,qty)values(?,?,?)");
    ps1.setString(1,"Keyborad");
    ps1.setInt(2,5000);
    ps1.setInt(3,500);
    int second = ps1.executeUpdate();
    System.out.println("Second Row Inserted but not commited");
    
    ps1 = con.prepareStatement("insert into product(pname,price,qty)values(?,?,?)");
    ps1.setString(1,"Printer");
    ps1.setInt(2,10000);
    ps1.setInt(3,100);
    int third = ps1.executeUpdate();
    System.out.println("Third Row Inserted but not commited");
    
    
    /*Commit a trasaction */    
    con.commit();
    System.out.println("Transaction Commitedddddd");  
  } catch (ClassNotFoundException | SQLException e)
                {
   
   e.printStackTrace();
  }
  
  
 }

}

I have attached the video tutorial below it will help you  to do this  step by step.

 

admin

Recent Posts

Fish Inventory Shop Management System in Angular

This article explain how to make a Fish Inventory Management App in Angular.this app explain…

6 days ago

Fish Inventory Management with React

Introduction to Fish Inventory Management In the aquaculture industry, managing fish inventory is crucial for…

1 week ago

Java GUI CRUD for Beginners

Introduction to Java GUI CRUD Java is a powerful programming language widely used for building…

1 week ago

Creating Beautiful Login Form Design Using React

Introduction to Login Form Design Designing an effective and beautiful login form is crucial for…

2 weeks ago

Creating Responsive Login Form with React

Introduction In today creating a responsive login form is essential for providing a seamless user…

2 weeks ago

Master React Inventory Management System Development

Introduction to Inventory Management Systems In today's fast-paced digital environment, businesses require efficient inventory management…

3 weeks ago