Added lastinsertId method

And fixed the sql writing to log.