Truncating and Deleting Table
What we would like to achieve in this topic is to empty a table completely and get rid of it. In order to empty the table, we could simply formulate DELETE
statements that match every record in our table and thus remove every single record from our table. However, there is a more elegant way. We can use the TRUNCATE TABLE
SQL statement. The result of this statement is a literally empty table. We can use the Exec()
function from our sql
package. You already know how to initialize the package with imports. You also know how to connect to the database. This time, we only focus on the statements.
The following statement will achieve a full TRUNCATE
:
EmptyTable, EmptyTableErr := db.Exec("TRUNCATE TABLE test") if EmptyTableErr != nil { panic(EmptyTableErr) }
The result of this is an empty table called test
.
In order to get rid of the table completely, we should modify our statement as follows.
DropTable, DropTableErr := db...