Execute Multiple SQL Statements in a Single String with Go
SQL dumps generated by mysqldump often contain multiple statements that need to be executed sequentially to set up a database. Finding a MySQL driver for Go that can handle this task can be challenging.
Existing Drivers with Limitations
Common drivers like Go-MySQL-Driver and MyMySQL lack support for executing multiple statements in a single string. Attempts to execute such statements will result in errors.
Go-MySQL-Driver: Enabling Multi-Statement Support
The go-sql-driver/mysql driver offers a solution by allowing you to set the multiStatements=true connection parameter. This parameter enables the execution of multiple statements within a single string.
package main import ( "database/sql" "log" _ "github.com/go-sql-driver/mysql" ) func main() { db, err := sql.Open("mysql", "user:password@(127.0.0.1:3306)/?multiStatements=true") if err != nil { log.Println(err) } sql := "DROP SCHEMA IF EXISTS foo; CREATE SCHEMA IF NOT EXISTS foo;" _, err = db.Exec(sql) if err != nil { log.Println(err) } db.Close() }
By setting multiStatements=true, the driver will execute both statements in the string, successfully creating the foo schema. It's important to note that the driver's documentation warns against using this option due to potential issues with transactions and other limitations.
The above is the detailed content of How Can I Execute Multiple SQL Statements in a Single String Using Go\'s MySQL Driver?. For more information, please follow other related articles on the PHP Chinese website!