factored sql prepare code
safer result checking for count, should fix #7