How to establish connection to a database
import [Link];
import [Link];
import [Link];
public class MySQLConnectionExample {
public static void main(String[] args) {
// MySQL connection details
String url = "jdbc:mysql://localhost:3306/testdb"; // Replace
`testdb` with your database name
String username = "root"; // Replace with your MySQL
username
String password = "your_password"; // Replace with your
MySQL password
try {
// Load the MySQL JDBC driver
[Link]("[Link]");
// Establish the connection
Connection conn = [Link](url, username,
password);
[Link]("Connection established successfully!");
// Close the connection
[Link]();
} catch (ClassNotFoundException e) {
[Link]("MySQL JDBC Driver not found.");
[Link]();
} catch (SQLException e) {
[Link]("Connection failed.");
[Link]();
}
}
}
Use of executeUpdate
import [Link].*;
public class InsertUpdateExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb"; // Replace with
your DB name
String user = "root"; // Your MySQL username
String password = "your_password"; // Your MySQL password
try {
[Link]("[Link]");
Connection conn = [Link](url, user,
password);
// -------- INSERT Operation --------
String insertQuery = "INSERT INTO students (name, age) VALUES
(?, ?)";
PreparedStatement insertStmt =
[Link](insertQuery);
[Link](1, "John");
[Link](2, 20);
int rowsInserted = [Link]();
[Link](rowsInserted + " row(s) inserted.");
// -------- UPDATE Operation --------
String updateQuery = "UPDATE students SET age = ? WHERE
name = ?";
PreparedStatement updateStmt =
[Link](updateQuery);
[Link](1, 21);
[Link](2, "John");
int rowsUpdated = [Link]();
[Link](rowsUpdated + " row(s) updated.");
[Link]();
} catch (Exception e) {
[Link]();
}
}
}
Use of result set
import [Link].*;
public class ResultSetExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb"; // Your database
URL
String user = "root"; // Your MySQL username
String password = "your_password"; // Your MySQL password
try {
// Load MySQL JDBC Driver
[Link]("[Link]");
// Establish connection
Connection conn = [Link](url, user,
password);
// Create a SQL SELECT query
String query = "SELECT * FROM students";
// Create a Statement or PreparedStatement
Statement stmt = [Link]();
// Execute the query and store the result
ResultSet rs = [Link](query);
// Loop through the ResultSet
[Link]("Student Records:");
while ([Link]()) {
int id = [Link]("id"); // use column name or index
String name = [Link]("name");
int age = [Link]("age");
[Link]("ID: " + id + ", Name: " + name + ", Age: " +
age);
}
// Close connections
[Link]();
[Link]();
[Link]();
} catch (Exception e) {
[Link]();
}
}
}