Connection conn = DriverManager.getConnection(url, username, password); String query = "SELECT * FROM users WHERE id = ?"; PreparedStatement stmt = conn.prepareStatement(query); stmt.setInt(1, userId); // set the value of parameter in query ResultSet rs = stmt.executeQuery();
Connection conn = dataSource.getConnection(); String insertQuery = "INSERT INTO users (id, name, email) VALUES (?, ?, ?)"; PreparedStatement stmt = conn.prepareStatement(insertQuery); stmt.setInt(1, userId); stmt.setString(2, userName); stmt.setString(3, userEmail); stmt.executeUpdate();In the above example, we use a dataSource to get a connection to a database. Then we create an INSERT query with placeholders for three parameters. We create a new PreparedStatement object using prepareStatement method and set the values for each parameter. Finally, we execute the query using executeUpdate method. Package library used in the example is javax.sql.