How to use MySQL and Go language to develop a simple online investment platform
Introduction:
As a digital financial service, the development of online investment platforms is increasingly attracted people's attention. This article will introduce how to use MySQL and Go language to develop a simple online investment platform, including database design and related code examples.
import (
"database/sql" "fmt" "log" _ "github.com/go-sql-driver/mysql"
)
func connectDB() (*sql.DB, error) {
db, err := sql.Open("mysql", "username:password@tcp(localhost:3306)/database_name") if err != nil { log.Fatal(err) return nil, err } err = db.Ping() if err != nil { log.Fatal(err) return nil, err } fmt.Println("Connected to the database!") return db, nil
}
import (
"database/sql" "fmt" "log" "net/http"
)
func registerUser(w http.ResponseWriter, r *http.Request) {
username := r.FormValue("username") password := r.FormValue("password") email := r.FormValue("email") db, err := connectDB() if err != nil { log.Fatal(err) http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } defer db.Close() stmt, err := db.Prepare("INSERT INTO User (Username, Password, Email) VALUES (?, ?, ?)") if err != nil { log.Fatal(err) http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } defer stmt.Close() _, err = stmt.Exec(username, password, email) if err != nil { log.Fatal(err) http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } fmt.Fprintln(w, "Registration successful!")
}
import (
"database/sql" "fmt" "log" "net/http"
)
type Investment struct {
ID int Name string Amount float64 ExpectedReturn float64 InvestmentTerm int
}
func getInvestmentList(w http.ResponseWriter, r *http.Request) {
db, err := connectDB() if err != nil { log.Fatal(err) http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } defer db.Close() rows, err := db.Query("SELECT * FROM Investment") if err != nil { log.Fatal(err) http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } defer rows.Close() var investments []Investment for rows.Next() { var investment Investment err := rows.Scan(&investment.ID, &investment.Name, &investment.Amount, &investment.ExpectedReturn, &investment.InvestmentTerm) if err != nil { log.Fatal(err) http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } investments = append(investments, investment) } for _, investment := range investments { fmt.Fprintf(w, "ID: %d, Name: %s, Amount: %.2f, Expected Return: %.2f%%, Investment Term: %d months
", investment.ID, investment.Name, investment.Amount, investment.ExpectedReturn, investment.InvestmentTerm)
}
}
The above is the detailed content of How to develop a simple online investment platform using MySQL and Go language. For more information, please follow other related articles on the PHP Chinese website!