task 9
Fri Nov 01 2024 15:44:41 GMT+0000 (Coordinated Universal Time)
Saved by
@sem
package task9;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class preparedstmt {
// Database credentials and URL
static final String JDBC_URL = "jdbc:mysql://localhost:3306/varshitha"; // Replace with your database name
static final String JDBC_USER = "root"; // Replace with your MySQL username
static final String JDBC_PASSWORD = "root"; // Replace with your MySQL password
public static void main(String[] args) {
// SQL query to insert data into the Students table
String insertSQL = "INSERT INTO Students (name, age, grade) VALUES (?, ?, ?)";
// Try with resources to automatically close the connection and statement
try (Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD);
PreparedStatement preparedStatement = connection.prepareStatement(insertSQL)) {
// Insert first student
preparedStatement.setString(1, "Alice");
preparedStatement.setInt(2, 20);
preparedStatement.setString(3, "A");
preparedStatement.executeUpdate();
System.out.println("Inserted first student: Alice");
// Insert second student
preparedStatement.setString(1, "Bob");
preparedStatement.setInt(2, 22);
preparedStatement.setString(3, "B");
preparedStatement.executeUpdate();
System.out.println("Inserted second student:s Bob");
} catch (SQLException e) {
System.out.println("SQL Exception: " + e.getMessage());
}
}
}
content_copyCOPY
Comments