Unit2-CRUD-AdditionalReference
Unit2-CRUD-AdditionalReference
USE testdb;
);
import java.sql.*;
readUsers(conn);
deleteUser(conn, 1);
} catch (SQLException e) {
e.printStackTrace();
public static void createUser(Connection conn, String name, String email) throws SQLException {
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
stmt.setString(1, name);
stmt.setString(2, email);
stmt.executeUpdate();
while (rs.next()) {
System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name") + ", Email: " +
rs.getString("email"));
}
}
public static void updateUser(Connection conn, int id, String name, String email) throws SQLException
{
stmt.setString(1, name);
stmt.setString(2, email);
stmt.setInt(3, id);
stmt.executeUpdate();
stmt.setInt(1, id);
stmt.executeUpdate();
/*
2. A 'users' table exists in 'testdb' with columns: id (INT, AUTO_INCREMENT, PRIMARY KEY), name
(VARCHAR), email (VARCHAR).
*/
// Advanced JDBC Connection with PreparedStatement and Error Handling
import java.sql.*;
readUsers(conn);
deleteUser(conn, 1);
} catch (SQLException e) {
public static void createUser(Connection conn, String name, String email) throws SQLException {
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
stmt.setString(1, name);
stmt.setString(2, email);
stmt.executeUpdate();
}
public static void readUsers(Connection conn) throws SQLException {
while (rs.next()) {
System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name") + ", Email: " +
rs.getString("email"));
public static void updateUser(Connection conn, int id, String name, String email) throws SQLException
{
stmt.setString(1, name);
stmt.setString(2, email);
stmt.setInt(3, id);
stmt.executeUpdate();
stmt.setInt(1, id);
stmt.executeUpdate();
}
}