Closed sohamkumar05 closed 6 years ago
Your program is wrong. There is no error in the driver.
I may be wrong because of the mysql and mariadb version since I don't know how to find it. Please let me know what is wrong in the code. The about code displays all the ename from a table named employee to the web browser.
I'm assuming this is an example/test learning program because there are several logic issues but, as a simple example of how to start fixing your program, I created the DB and populated some rows using MySQL Random Data Generator. The generated rows are:
mysql> select * from employee;
+---------------------------+------------------------------------------+----------------------+--------------+---------+
| ename | street | city | joining_date | gender |
+---------------------------+------------------------------------------+----------------------+--------------+---------+
| Alan Montgomery | sit quia cumque est velit. | Annie Parker | 2017-12-29 | Amy |
| Brian Brooks | nisi neque porro qui. | Michelle Griffin | 2017-12-29 | Edward |
| Cynthia Lawrence | ea minus odit minus laborum aut. | NULL | 2017-12-29 | Christi |
| Eric Ferguson | est esse sapiente eos quas ut aut eum fa | Mr. Dr. Johnny Vasqu | 2017-12-29 | NULL |
| Eugene Hall Jr. Sr. I II | non corporis tenetur dolorem ut officiis | Chris Holmes | 2017-12-29 | Elizabe |
| Heather Cooper | blanditiis inventore maiores reprehender | Amanda Morales | 2017-12-29 | Rebecca |
| Irene Medina | quam sint qui et dolor cum. | Maria Simmons | 2017-12-29 | Matthew |
| Judy Kim | error cupiditate officia rerum odio temp | Norma Washington | 2017-12-29 | Nancy |
| Julie Richards | nihil velit fuga pariatur quis. | Carlos Lopez | 2017-12-29 | Janet |
| Kevin Nichols Jr. Sr. I I | sint rem quia! | Beverly Perkins I II | 2017-12-29 | Eric |
| Lillian Bell | enim sed dolorum natus ad ea similique t | Tammy Mason | 2017-12-29 | Kathy |
| Mr. Dr. Jack Gilbert | NULL | Nancy Miller | 2017-12-29 | Fred |
| Mrs. Ms. Miss Janet Rose | voluptatum numquam autem eaque maiores i | NULL | 2017-12-29 | Patrici |
| Mrs. Ms. Miss Judy Barnes | laborum consequatur illum minus deleniti | Linda Morgan | 2017-12-29 | Terry |
| Patricia Greene I II III | dignissimos minus reiciendis! | Keith Hall | 2017-12-29 | Philip |
| Patricia Patterson | harum odio enim autem sed qui! | NULL | 2017-12-29 | Arthur |
| Ralph Fowler | laboriosam officia sint dolor harum alia | Jerry Bell | 2017-12-29 | Roy |
| Roger Campbell | quo ipsam et tenetur et vel. | Harry Edwards | 2017-12-29 | Sharon |
| Willie Bell | est iusto alias. | Steven Bradley | 2017-12-29 | Debra |
+---------------------------+------------------------------------------+----------------------+--------------+---------+
19 rows in set (0.00 sec)
and here is a small working version of your code:
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"os"
"text/template"
_ "github.com/go-sql-driver/mysql"
)
type templateData struct {
Name []string
}
var conn *sql.DB
func main() {
// At the very beginning, connect to the database and store the connection in
// a global variable. You shouldn't connect to the db on each request.
var err error
conn, err = sql.Open("mysql", "root:@tcp(127.0.0.1:3306)/comp")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Then, create the table if it doesn't exists
_, err = conn.Exec("create table if not exists employee(ename varchar(25) primary key,street varchar(40),city varchar(20),joining_date date,gender varchar(7))")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
http.HandleFunc("/", myHandlerFunc)
http.ListenAndServe(":8000", nil)
}
func myHandlerFunc(w http.ResponseWriter, req *http.Request) {
rows, err := conn.Query("select ename from employee")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("cannot read the database"))
log.Printf("cannot read the db: %s", err)
// don't use os.Exit from a func, just return
// os.Exit(1)
return
}
var td templateData
for rows.Next() {
// If the SELECT is retrieving the ename column, the
// variable name should be ename and not title, not mandatory
// but it makes more sense
var ename string
err := rows.Scan(&ename)
if err != nil {
continue
}
td.Name = append(td.Name, ename)
}
// don't forget to check for errors
if rows.Err() != nil {
log.Printf("Cannot run the query: %s", err)
return
}
// and don't forget to close the query connection
rows.Close()
w.Header().Add("Content Type", "text/html")
tmpl, err := template.New("anyNameForTemplate").Parse(doc)
if err == nil {
err = tmpl.Execute(w, td)
if err != nil {
log.Println(err)
}
}
}
const doc = `
<title>First Template</title>
names<br>
{{range .Name}}
{{.}}<br>
{{end}}
`
Thanks a lot The issue is solved
giving error statement expects 0 inputs;got 1
package main
import( "fmt" "database/sql" "net/http" _ "github.com/go-sql-driver/mysql" "text/template" "os")
func main(){ http.HandleFunc("/",myHandlerFunc) http.ListenAndServe(":8000", nil) }
func myHandlerFunc(w http.ResponseWriter, req *http.Request) { conn,err:=sql.Open("mysql","root:@tcp(127.0.0.1:3306)/comp") if err != nil{ fmt.Println(err) os.Exit(1) } state,err:=conn.Prepare("create table if not exists employee(ename varchar(25) primary key,street varchar(40),city varchar(20),joining_date date,gender varchar(7))") if err != nil{ fmt.Println(err) os.Exit(1) } rows,err:=state.Query("select
ename
fromemployee
") if err != nil{ fmt.Println(err) os.Exit(1) } for rows.Next(){ var title string rows.Scan(&title) Name = append(Name, title)} w.Header().Add("Content Type", "text/html") tmpl, err := template.New("anyNameForTemplate").Parse(doc) if err == nil { // tmpl.Execute(w, req.URL.Path) tmpl.Execute(w, req.URL.Path[1:]) } conn.Close() }
const doc = ` <!DOCTYPE html>
names
{{range .Name}}- {{.}}
{{end}}
`
Configuration
Driver version (or git SHA):
go version: go 1.9.2 windows/amd64
Server version: E.g. MySQL 5.6, MariaDB 10.0.20 Windows 8.1