Moritz Schmidt 9 年之前
當前提交
020f9a8bf8
共有 2 個文件被更改,包括 53 次插入0 次删除
  1. 1 0
      README.md
  2. 52 0
      databaseutils.go

+ 1 - 0
README.md

@@ -0,0 +1 @@
+Database Utils for Go

+ 52 - 0
databaseutils.go

@@ -0,0 +1,52 @@
+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
+}