我正在从表单中读取MySQL查询输入:
<h1>MySQL Page</h1>
<small>Perform queries and edit the database from here</small>
<form method="get" action="">
<label for="sqlQuery">MySQL Query:</label>
<input type="text" id="sqlQuery" name="sqlQuery">
<button type="submit">Perform Query</button>
</form>
之后我想使用GoLang在同一页面上显示结果,但它一直告诉我:
# command-line-arguments
./sql.go:128: cannot convert results (type sql.Result) to type string
请记住,这是我写过的第一个golang应用程序,所以如果这是一个简单的问题,我很抱歉,这里是golang代码:
func sqlQueryHandler(response http.ResponseWriter, request *http.Request){
userName := getUserName(request)
db, err := sql.Open("mysql", userName)
fmt.Fprintf(response, sqlPage)
sqlCommand := request.FormValue("sqlQuery")
//fmt.Fprintf(response, sqlCommand)
if err != nil {
fmt.Fprintf(response, "\n\nAn error occured during your MySQL command: %s", err)
panic(err)
} else {
data, err := db.Exec(sqlCommand)
if err != nil {
http.Redirect(response, request, "/error", 302)
} else {
// display the output of the sql query here
}
}
}
答案 0 :(得分:1)
这是一个基于您的代码的示例:
func sqlQueryHandler(response http.ResponseWriter, request *http.Request) {
var (
userName = getUserName(request)
sqlCommand = request.FormValue("sqlQuery")
)
db, err := sql.Open("mysql", userName)
if err != nil {
fmt.Fprintf(response, "\n\nAn error occured during your MySQL command: %s", err)
// if you panic you stop here anyway. no else needed
panic(err)
}
rows, err := db.Query(sqlCommand)
if err != nil {
http.Redirect(response, request, "/error", 302)
// return, so no else is needed
return
}
if err != nil {
panic(err)
}
defer rows.Close()
for rows.Next() {
var (
name string
age int
)
if err := rows.Scan(&name, &age); err != nil {
panic(err)
}
fmt.Printf("%s is %d\n", name, age)
}
if err := rows.Err(); err != nil {
panic(err)
}
}
但是这种方法有几个问题:
typed language
范例相矛盾的通用SQL查询函数。你可以编写处理不同结构化数据的一般函数(比如json.Unmarshal()
) - 但特别是在编程的早期你不应该这样做。