MySQL Database Insert & Get Last Insert ID
·
394 words
·
2 minutes read
This post aims to show you how to use the go-sql-driver
(which uses the database/sql
interface) to insert a row into a MySQL database table.
To do this we use the Open()
method to create our database object (and connection pool). We can then create an sql statement using Prepare()
and pass in our parameters into Exec()
, matching them up with question marks (to avoid sql injection). Finally, calling the LastInsertId()
we can get the id of the row we’ve just inserted - and in our example, we output this value to screen.
To get this example to work you’ll need to fill in the DB_DSN constant. The go-sql-driver has a guide on github to help with this.
|
|
It’s important to note that the sql.Open()
does not actually create a connection (or test it fully), so by only testing for an error here can be misleading. If you want/need to test that the DSN is valid before using it, you can add some code like this before using the db object.
|
|