| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- package databaseutils
- import (
- "database/sql"
- _ "github.com/go-sql-driver/mysql"
- "fmt"
- )
- type DBUtils struct {
- User string
- Password string
- Host string
- Database string
- Handle *sql.DB
- }
- // db := dbUtils{"root", "root", "127.0.0.1", "gotest"}
- func (dbUtil DBUtils) Connect() {
- var err error
- dbUtil.Handle, err = sql.Open("mysql", dbUtil.User + ":" + dbUtil.Password + "@tcp(" + dbUtil.Host + ")/" + dbUtil.Database)
- if err != nil {
- panic(err.Error()) // Just for example purpose. You should use proper error handling instead of panic
- }
- // Open doesn't open a connection. Validate DSN data:
- err = dbUtil.Handle.Ping()
- if err != nil {
- panic(err.Error()) // proper error handling instead of panic in your app
- }
- fmt.Printf("%v", dbUtil)
- }
- func (dbUtil DBUtils) Close() {
- dbUtil.Handle.Close()
- }
- func (dbUtil DBUtils) GetString(what string, from string, where string, wherevalue string) string {
- var username string
- fmt.Printf("%v", dbUtil)
- stmtOut, err := dbUtil.Handle.Prepare("SELECT " + what + " FROM " + from + " WHERE " + where + " = " + wherevalue)
- if err != nil {
- panic(err.Error()) // proper error handling instead of panic in your app
- }
- err = stmtOut.QueryRow(1).Scan(&username)
- return username
- }
|