Use prepared statements and transactions on the SQL queries

The commit messages explain the changes.