Detailed explanation of JDBC 2.0 Optional Package framework in the Java class library detailed explanation
Detailed explanation of JDBC 2.0 Optional Package framework in the Java class library detailed explanation
JDBC (Java DataBase Connectivity) is a standard API for Java language to interact with various relational databases.JDBC 2.0 Optional Package is a framework introduced in the JDK 1.2 version, adding many new features and functions to JDBC.This article will introduce the framework of JDBC 2.0 Optional Package and some example code.
JDBC 2.0 Optional Package framework is mainly composed of two parts: javax.sql package and javax.transaction.xa package.
The Javax.SQL package provides some new interfaces and classes to enhance the flexibility and performance of database operations.The most important interfaces are Connection, Statement and ResultSet, which are the core interfaces for database operations.In addition, there are some new interfaces and classes, which are used to process the metadata information, pre -processing statements, preservation points and batch processing of databases.
Below is a sample code for database query using JDBC 2.0 Optional Package:
import java.sql.*;
public class JDBCExample {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Load the database drive
Class.forName("com.mysql.jdbc.Driver");
// Create a database connection
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
// Create a statement object
stmt = conn.createStatement();
// Execute the query sentence
rs = stmt.executeQuery("SELECT * FROM employees");
// Treatment results set
while (rs.next()) {
System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Close the database connection
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Javax.transaction.xa package provides some interfaces and classes for distributed transactions.With these interfaces and classes, the atomicity and consistency of multiple database operations can be achieved, ensuring that all related operations in the distributed system are all successful or all failed.
Below is a sample code for distributed transactions using JDBC 2.0 Optional Package:
import java.sql.*;
import javax.sql.*;
import javax.transaction.xa.*;
public class DistributedTransactionExample {
public static void main(String[] args) {
Connection conn1 = null;
Connection conn2 = null;
XAConnection xaConn1 = null;
XAConnection xaConn2 = null;
XAResource xaRes1 = null;
XAResource xaRes2 = null;
Xid xid = null;
try {
// Load the database drive
Class.forName("com.mysql.jdbc.Driver");
// Create a database connection
conn1 = DriverManager.getConnection("jdbc:mysql://localhost:3306/database1", "username", "password");
conn2 = DriverManager.getConnection("jdbc:mysql://localhost:3306/database2", "username", "password");
// Create xaresource objects
XADataSource xaDataSource1 = ((XADataSource) Class.forName("com.mysql.jdbc.jdbc2.optional.MysqlXADataSource").newInstance());
XADataSource xaDataSource2 = ((XADataSource) Class.forName("com.mysql.jdbc.jdbc2.optional.MysqlXADataSource").newInstance());
xaDataSource1.setUrl("jdbc:mysql://localhost:3306/database1");
xaDataSource1.setUser("username");
xaDataSource1.setPassword("password");
xaDataSource2.setUrl("jdbc:mysql://localhost:3306/database2");
xaDataSource2.setUser("username");
xaDataSource2.setPassword("password");
xaConn1 = xaDataSource1.getXAConnection();
xaConn2 = xaDataSource2.getXAConnection();
xaRes1 = xaConn1.getXAResource();
xaRes2 = xaConn2.getXAResource();
// Create global affairs ID
xid = new MyXid(100, new byte[]{0x01}, new byte[]{0x02});
// Start global affairs
xaRes1.start(xid, XAResource.TMNOFLAGS);
xaRes2.start(xid, XAResource.TMNOFLAGS);
// Execute the database operation
PreparedStatement stmt1 = conn1.prepareStatement("INSERT INTO table1 (id, name) VALUES (?, ?)");
stmt1.setInt(1, 1);
stmt1.setString(2, "John");
stmt1.execute();
PreparedStatement stmt2 = conn2.prepareStatement("INSERT INTO table2 (id, name) VALUES (?, ?)");
stmt2.setInt(1, 1);
stmt2.setString(2, "Smith");
stmt2.execute();
// Submit global affairs
xaRes1.end(xid, XAResource.TMSUCCESS);
xaRes2.end(xid, XAResource.TMSUCCESS);
int xaRes1PrepareResult = xaRes1.prepare(xid);
int xaRes2PrepareResult = xaRes2.prepare(xid);
if (xaRes1PrepareResult == XAResource.XA_OK && xaRes2PrepareResult == XAResource.XA_OK) {
xaRes1.commit(xid, false);
xaRes2.commit(xid, false);
} else {
xaRes1.rollback(xid);
xaRes2.rollback(xid);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (XAException e) {
e.printStackTrace();
try {
xaRes1.rollback(xid);
xaRes2.rollback(xid);
} catch (XAException ex) {
ex.printStackTrace();
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} finally {
// Close the database connection
try {
if (conn1 != null) conn1.close();
if (conn2 != null) conn2.close();
if (xaConn1 != null) xaConn1.close();
if (xaConn2 != null) xaConn2.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
class MyXid implements Xid {
private int formatId;
private byte[] globalTransactionId;
private byte[] branchQualifier;
public MyXid(int formatId, byte[] globalTransactionId, byte[] branchQualifier) {
this.formatId = formatId;
this.globalTransactionId = globalTransactionId;
this.branchQualifier = branchQualifier;
}
public int getFormatId() {
return this.formatId;
}
public byte[] getGlobalTransactionId() {
return this.globalTransactionId;
}
public byte[] getBranchQualifier() {
return this.branchQualifier;
}
}
The above is a detailed introduction and code example of the JDBC 2.0 Optional Package framework.Through this framework, we can operate the database more flexibly and achieve distributed transactions.It provides a powerful and easy -to -use tool for Java developers, making the interaction with the database more convenient and efficient.