在Go语言中使用MySQL的动态条件查询实际上是很简单的。可以使用数据库/ SQL包提供的预处理语句。下面是一个示例代码,以便您快速了解这个过程:
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
// Open database connection
db, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/dbname")
if err != nil {
fmt.Println(err.Error())
return
}
defer db.Close()
// Prepare statement
stmt, err := db.Prepare("SELECT name FROM users WHERE age=?")
if err != nil {
fmt.Println(err.Error())
return
}
defer stmt.Close()
// Execute the query
rows, err := stmt.Query(25)
if err != nil {
fmt.Println(err.Error())
return
}
defer rows.Close()
// Get results
var name string
for rows.Next() {
err := rows.Scan(&name)
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Println(name)
}
err = rows.Err()
if err != nil {
fmt.Println(err.Error())
return
}
}
SELECT name FROM users WHERE age=?Query