Create cursor object inside the with statement

This may solve #761.