Click here to Skip to main content
16,017,351 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
PS C:\Users\dddd\go\src\Hdddd> go run main.go
*******browse Handler running*******
2022/11/14 14:01:44 http: panic serving 127.0.0.1:65343: runtime error: invalid memory address or nil pointer dereference
goroutine 26 [running]:
net/http.(*conn).serve.func1()
        C:/Program Files/Go/src/net/http/server.go:1850 +0xbf
panic({0x8d9fe0, 0xbd0880})
        C:/Program Files/Go/src/runtime/panic.go:890 +0x262
database/sql.(*DB).conn(0x0, {0x9cad70, 0xc00009e010}, 0x1)
        C:/Program Files/Go/src/database/sql/sql.go:1288 +0x53


What I have tried:

Go
  1  package main
  2  
  3  import (
  4  	"database/sql"
  5  	"fmt"
  6  	"html/template"
  7  	"net/http"
  8  
  9  	_ "github.com/go-sql-driver/mysql"
 10  )
 11  
 12  type Employee struct {
 13  	Id             int
 14  	EmpName        string
 15  	Designation    string
 16  	DepartmentName string
 17  	PhoneNumber    string
 18  	Emailid        string
 19  }
 20  
 21  var tpl *template.Template
 22  
 23  var db *sql.DB
 24  var err error
 25  
 26  func main() {
 27  
 28  	tpl, err = template.ParseGlob("templates/*.html")
 29  
 30  	if err != nil {
 31  		fmt.Println(err.Error())
 32  	}
 33  
 34  	db, err := sql.Open("mysql", "root:Hdddd&@tcp(localhost:3306)/Embloyees")
 35  
 36  	if err != nil {
 37  		fmt.Println(err.Error())
 38  
 39  	}
 40  	defer db.Close()
 41  	//mux := http.NewRouter()
 42  	http.HandleFunc("/insert", insertHandler)
 43  	http.HandleFunc("/browse", browseHandler)
 44  	http.HandleFunc("/update", updateHandler)
 45  	http.HandleFunc("/delete", deleteHandler)
 46  	http.HandleFunc("/", homePageHandler)
 47  	http.ListenAndServe("localhost:8080", nil)
 48  
 49  }
 50  
 51  func browseHandler(w http.ResponseWriter, r *http.Request) {
 52  
 53  	fmt.Println("*******browse Handler running*******")
 54  	rows, err := db.Query("SELECT * FROM NewEmployee")
 55  	if err != nil {
 56  		panic(err)
 57  	}
 58  	defer rows.Close()
 59  	var employee []Employee
 60  	for rows.Next() {
 61  		var e Employee
 62  
 63  		err = rows.Scan(&e.Id, &e.EmpName, &e.Designation, &e.DepartmentName, &e.PhoneNumber, &e.Emailid)
 64  		if err != nil {
 65  			panic(err)
 66  		}
 67  		employee = append(employee, e)
 68  	}
 69  	tpl.ExecuteTemplate(w, "select.html", employee)
 70  }
 71  
 72  func insertHandler(w http.ResponseWriter, r *http.Request) {
 73  
 74  	fmt.Println("*******insert Handler running*******")
 75  	if r.Method == "GET" {
 76  		tpl.ExecuteTemplate(w, "insert.html", nil)
 77  		return
 78  	}
 79  	r.ParseForm()
 80  
 81  	name := r.FormValue("EmpName")
 82  	designation := r.FormValue("Designation")
 83  	department := r.FormValue("DepartmentName")
 84  	phone := r.FormValue("PhoneNumber")
 85  	Email := r.FormValue("Emailid")
 86  
 87  	if name == "" || designation == "" || department == "" || phone == "" || Email == "" {
 88  		fmt.Println("Error inseerting row:")
 89  		tpl.ExecuteTemplate(w, "insert.html", "Error inserting data, please check all fields.")
 90  		return
 91  	}
 92  	var ins *sql.Stmt
 93  	ins, err := db.Prepare("INSERT INTO NewEmployee ('EmpName', 'Designation', 'DepartmentName','PhoneNumber','Emailid') VALUES (?, ?, ?,?,?);")
 94  
 95  	if err != nil {
 96  		panic(err)
 97  	}
 98  	defer ins.Close()
 99  
100  	res, err := ins.Exec(name, designation, department, phone, Email)
101  
102  	rowsAffec, _ := res.RowsAffected()
103  	if err != nil || rowsAffec != 1 {
104  		fmt.Println("Error inserting row:", err)
105  		tpl.ExecuteTemplate(w, "insert.html", "Error inserting data, please check all fields.")
106  		return
107  	}
108  	lastInserted, _ := res.LastInsertId()
109  	rowsAffected, _ := res.RowsAffected()
110  	fmt.Println("ID of last row inserted:", lastInserted)
111  	fmt.Println("number of rows affected:", rowsAffected)
112  	tpl.ExecuteTemplate(w, "insert.html", "Product Successfully Inserted")
113  }
114  func updateHandler(w http.ResponseWriter, r *http.Request) {
115  
116  	fmt.Println("*****updateHandler running*****")
117  	r.ParseForm()
118  	id := r.FormValue("idemployee")
119  	row := db.QueryRow("SELECT * FROM NewEmbloyee WHERE idemployee = ?;", id)
120  	var e Employee
121  
122  	err := row.Scan(&e.Id, &e.EmpName, &e.Designation, &e.DepartmentName, &e.PhoneNumber, &e.Emailid)
123  	if err != nil {
124  		fmt.Println(err)
125  		http.Redirect(w, r, "/browse", http.StatusMovedPermanently)
126  		return
127  	}
128  	tpl.ExecuteTemplate(w, "update.html", e)
129  }
130  
131  func deleteHandler(w http.ResponseWriter, r *http.Request) {
132  
133  	fmt.Println("*****deleteHandler running*****")
134  	r.ParseForm()
135  	id := r.FormValue("idemployee")
136  
137  	del, err := db.Prepare("DELETE FROM NewEmployee WHERE ('idemployee' = ?);")
138  	if err != nil {
139  		panic(err)
140  	}
141  	defer del.Close()
142  	var res sql.Result
143  	res, err = del.Exec(id)
144  	rowsAff, _ := res.RowsAffected()
145  	fmt.Println("rowsAff:", rowsAff)
146  
147  		if err != nil || rowsAff != 1 {
148  			fmt.Fprint(w, "Error deleting product")
149  			return
150  		}
151  		fmt.Println("err:", err)
152  		tpl.ExecuteTemplate(w, "result.html", "Product was Successfully Deleted")
153  	}
154  func homePageHandler(w http.ResponseWriter, r *http.Request) {
155  
156  	http.Redirect(w, r, "/browse", http.StatusMovedPermanently)
157  }
Posted
Updated 17-Nov-22 22:21pm
v7
Comments
Richard MacCutchan 14-Nov-22 4:49am    
You need to indicate exactly which line caused the error. And if you look at that line you should be able to determine which variable does not contain a valid address/reference.
Richard MacCutchan 18-Nov-22 9:24am    
At a guess the error occurs on line 54, when err is not nil and you call panic. So you need to investigate what the problem is there; I suspect that db is the nil pointer.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900