how to attach an image to a custom post type in wordpress using just code

WP 3.1 introduces set_post_thumbnail() function, that sets attachment (that you will need to create first, you seem to be on right track with wp_insert_atachment()) as thumbnail for the post.