I'm reading a MySQL query input from a form:
<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>
After that I want to display the results on the same page using GoLang, however it keeps telling me that:
# command-line-arguments
./sql.go:128: cannot convert results (type sql.Result) to type string
Please keep in mind, this is the first golang app I've ever written so I apologize if this is a simple issue, here is the golang code:
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, "
An 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
}
}
}
Here an example based on your code:
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, "
An 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
", name, age)
}
if err := rows.Err(); err != nil {
panic(err)
}
}
There are several problems however with this approach:
typed language
paradigm. You can write general function dealing with differently structured data (like json.Unmarshal()
) -- but especially early in programming go you shouldn't.