如何利用MySQL和Go語言開發一個簡單的線上投資平台
#簡介:
作為一種數位化的金融服務,線上投資平台的發展正日益受到人們的關注。本文將介紹如何利用MySQL和Go語言開發一個簡單的線上投資平台,包括資料庫設計和相關程式碼範例。
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)
}
}
以上是如何利用MySQL和Go語言開發一個簡單的線上投資平台的詳細內容。更多資訊請關注PHP中文網其他相關文章!