0% found this document useful (0 votes)
5 views

Lab 7

This program illustrates performing batch transactions with prepared statements in Java. It connects to a database, disables auto-commit, prepares an INSERT statement, adds multiple records to the batch, executes the batch to insert all records at once, commits the transaction if successful, and handles any errors. Key steps include preparing the statement, setting parameter values and adding to the batch multiple times, executing the batch to insert all records, and committing the transaction only if all inserts succeed.

Uploaded by

Kishan Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Lab 7

This program illustrates performing batch transactions with prepared statements in Java. It connects to a database, disables auto-commit, prepares an INSERT statement, adds multiple records to the batch, executes the batch to insert all records at once, commits the transaction if successful, and handles any errors. Key steps include preparing the statement, setting parameter values and adding to the batch multiple times, executing the batch to insert all records, and committing the transaction only if all inserts succeed.

Uploaded by

Kishan Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Lab 7: Write a program using TCP/IP socket between client and server and perform two-way

communication
Client :
BufferedReader br
import java.io.*; = new BufferedReader(
import java.net.*; new InputStreamReader(
s.getInputStream()));
class Client2 { BufferedReader kb
= new BufferedReader(
public static void main(String args[]) new InputStreamReader(System.in));
throws Exception while (true) {
{
Socket s = new Socket("localhost", 888); String str, str1;
while ((str = br.readLine()) != null) {
DataOutputStream dos System.out.println(str);
= new DataOutputStream( str1 = kb.readLine();
s.getOutputStream()); ps.println(str1);
}
BufferedReader br ps.close();
= new BufferedReader( br.close();
new InputStreamReader( kb.close();
s.getInputStream())); ss.close();
s.close();
BufferedReader kb System.exit(0);
= new BufferedReader(
new InputStreamReader(System.in)); } // end of while
String str, str1; }
}
while (!(str = kb.readLine()).equals("exit")) {

dos.writeBytes(str + "\n"); Output:


str1 = br.readLine();

System.out.println(str1);
}

// close connection.
dos.close();
br.close();
kb.close();
s.close();
}
}
Figure 1 Server
Server :

import java.io.*;
import java.net.*;
class Server2 {
public static void main(String args[])
throws Exception
{
ServerSocket ss = new ServerSocket(888);
Socket s = ss.accept();
System.out.println("Connection established");

// to send data to the client


PrintStream ps Figure 2 client
= new PrintStream(s.getOutputStream());
Lab 8: Write a program to illustrate JDBC connectivity and perform CRUD operation on a table
student/employee (at least 5 attributes)

import java.sql.*; stmt.executeUpdate(sql);

public class StudentDatabase { sql = "DELETE FROM student WHERE id = 1";


stmt.executeUpdate(sql);
static final String JDBC_DRIVER =
"com.mysql.jdbc.Driver"; sql = "SELECT * FROM student";
static final String DB_URL = ResultSet rs = stmt.executeQuery(sql);
"jdbc:mysql://localhost/student";
while (rs.next()) {
static final String USER = "root"; int id = rs.getInt("id");
static final String PASS = "password"; String name = rs.getString("name");
int age = rs.getInt("age");
public static void main(String[] args) { String gender = rs.getString("gender");
String grade = rs.getString("grade");
Connection conn = null; System.out.println("ID: " + id + ", Name: " +
Statement stmt = null; name + ", Age: " + age + ", Gender: " + gender + ", Grade:
" + grade);
try { }
Class.forName(JDBC_DRIVER);
rs.close();
conn = DriverManager.getConnection(DB_URL, stmt.close();
USER, PASS); conn.close();
} catch (SQLException se) {
stmt = conn.createStatement(); se.printStackTrace();
String sql = "CREATE TABLE IF NOT EXISTS } catch (Exception e) {
student " + e.printStackTrace();
"(id INTEGER not NULL } finally {
AUTO_INCREMENT, " + try {
" name VARCHAR(255), " + if (stmt != null) stmt.close();
" age INTEGER, " + } catch (SQLException se2) {
" gender VARCHAR(10), " + }
" grade VARCHAR(10), " + try {
" PRIMARY KEY ( id ))"; if (conn != null) conn.close();
stmt.executeUpdate(sql); } catch (SQLException se) {
sql = "INSERT INTO student (name, age, gender, se.printStackTrace();
grade) " + }
"VALUES ('Kishan Singh', 20, 'Male', 'A')"; }
stmt.executeUpdate(sql); }
}
sql = "UPDATE student SET grade = 'B' WHERE
id = 1";
Lab 9: Write a program to illustrate Batch Transaction with prepared statement

import java.sql.*;

public class BatchTransactionExample {


public static void main(String[] args) {
String jdbcUrl = "jdbc:mysql://localhost:3306/mydatabase";
String username = "myuser";
String password = "mypassword";

try (Connection conn = DriverManager.getConnection(jdbcUrl, username, password)) {


conn.setAutoCommit(false); // disable auto-commit

String insertQuery = "INSERT INTO customers (name, email) VALUES (?, ?)";
PreparedStatement ps = conn.prepareStatement(insertQuery);

ps.setString(1, "Prateek Verma");


ps.setString(2, "[email protected]");
ps.addBatch();

ps.setString(1, "Ajay Sngh");


ps.setString(2, "[email protected]");
ps.addBatch();

ps.setString(1, "Kishan Singh");


ps.setString(2, "[email protected]");
ps.addBatch();

int[] updateCounts = ps.executeBatch();

for (int i : updateCounts) {


if (i == Statement.EXECUTE_FAILED) {
throw new SQLException("Batch update failed");
}
}

conn.commit();
System.out.println("Batch transaction completed successfully");
} catch (SQLException e) {
System.err.println("Error: " + e.getMessage());
}
}
}

You might also like