import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class ConnectToDatabase { public static void main(String[] args) { Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost/mydb"; //replace mydb with your database name String user = "root"; String password = "password"; conn = DriverManager.getConnection(url, user, password); System.out.println("Database connection established"); } catch (ClassNotFoundException | SQLException ex) { System.err.println("Database connection error: " + ex.getMessage()); } } }
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class TransactionExample { public static void main(String[] args) { Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost/mydb"; //replace mydb with your database name String user = "root"; String password = "password"; conn = DriverManager.getConnection(url, user, password); conn.setAutoCommit(false); //start transaction Statement stmt = conn.createStatement(); stmt.executeUpdate("INSERT INTO employees VALUES ('John', 'Doe', 10000)"); stmt.executeUpdate("UPDATE employees SET salary = 12000 WHERE first_name = 'John'"); conn.commit(); //commit changes System.out.println("Transaction completed"); } catch (ClassNotFoundException | SQLException ex) { System.err.println("Database connection error: " + ex.getMessage()); try { if (conn != null) { conn.rollback(); //rollback changes in case of error } } catch (SQLException se) { System.err.println("Transaction rollback error: " + se.getMessage()); } } finally { try { if (conn != null) { conn.close(); } } catch (SQLException ex) { System.err.println("Connection close error: " + ex.getMessage()); } } } }Package library: java.sql In conclusion, the java.sql.Connection interface is a fundamental component of the JDBC API, providing methods to manage database connections, transactions, and SQL statements. The package library for these examples is java.sql.