import java.sql.
Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DatabaseConnection {
public static void main(String[] args) {
// Database connection parameters
String url = "jdbc:mysql://localhost:3306/ani"; // Update the database URL
if necessary
String user = "Arafath"; // Update with your MySQL username
String password = "sacet123"; // Update with your MySQL password
try {
// 1. Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// 2. Establish the connection
Connection conn = DriverManager.getConnection(url, user, password);
// 3. Check if the connection is successful
if (conn != null) {
System.out.println("Connected to the database successfully!");
// SQL statement to insert a new student
String sql = "INSERT INTO students (id, name, course) VALUES (?, ?,
?)";
PreparedStatement stmt = conn.prepareStatement(sql);
// Set the values for the new student record
stmt.setInt(1, 2); // Set the ID (change as needed)
stmt.setString(2, "Vijay"); // Set the name
stmt.setString(3, "AIML"); // Set the course
// Execute the insert operation
int rowsAffected = stmt.executeUpdate();
if (rowsAffected > 0) {
System.out.println("Data inserted successfully!");
} else {
System.out.println("Data insertion failed.");
}
// Close the PreparedStatement
stmt.close();
}
// 4. Close the connection
conn.close();
} catch (ClassNotFoundException e) {
System.out.println("JDBC Driver not found.");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("Database connection failed.");
e.printStackTrace();
}
}
}