我正在使用sqlx将我的 MySQL 数据库连接到 Golang。我有一个 SQL 模式,其中CREATE TABLE IF NOT EXISTS...
定义了所有语句。这里有一个例子:
CREATE TABLE IF NOT EXISTS `users`
(
`id` INT(0) NOT NULL auto_increment,
`language_code` VARCHAR(5) NOT NULL,
`premium` BIT(0) DEFAULT 0,
`status` VARCHAR(100) NOT NULL DEFAULT '',
`user_id` INT(0) NOT NULL,
PRIMARY KEY (id)
);
...
这里我如何连接到数据库并每次执行所有查询:
Database, err = sqlx.Connect(Config.Database.Type, Config.Database.DataSourceString) // Connect to the database
if err != nil { // If there's an error, handle it
panic(err.Error())
}
defer Database.Close() // Close the database when the function finishes
schemaSQL, err := ioutil.ReadFile("schema.sql") // Read the configuration file (DealsFinderBot/config.yaml)
if err != nil { // If there's an error, handle it
panic(err.Error())
}
for _, query := range strings.Split(string(schemaSQL), ";") { // Loop on the queries of the schema
if strings.TrimSpace(query) != "" { // If the query is not empty
Database.MustExec(query) // Execute the query
}
}
每次添加新列或编辑一些参数(如或)时,我都想更新(更改表)。我怎么能这样做?NOT NULL
DEFAULT ''