easysql encapsulated database operation, simplifying the use of the database.(include MySql,MsSQL database,more database is coming soon)
2.1 add mssql
2.0 v2 is coming, recode tx,optimize code and structure
...
1.2 add cache mode
1.1 add debug mode and debug func
1.0 finish all base func
go get -u -v github.com/JimYJ/easysql/mysql
github.com/Go-SQL-Driver/MySQL
import:
import mysql "github.com/JimYJ/easysql/mysql/v2"
conn db:
mysql.Init("127.0.0.1", 3306, "dbname", "root", "123","utf8mb4", MaxIdleConns, MaxOpenConns)
mysqldb, err := mysql.Getmysqldb()//singleton pattern
or
mysqldb, err := mysql.Newmysqldb("127.0.0.1", 3306, "dbname", "root", "123", MaxIdleConns, MaxOpenConns)
close conn:
mysqldb.Close()
set cache timeout
mysql.SetCacheTimeout(5 * time.Second)//default 5s. if want to set cache timeout,must before trun on cache else you set timeout is no work
use cache:
mysql.UseCache()
close cache:
mysql.CloseCache()
get value:
value,err := mysqldb.GetVal("SELECT count(*) FROM users")
or
value,err := mysqldb.GetVal("SELECT count(*) FROM users where type = ?","public")
get single row data:
row,err := mysqldb.GetRow("SELECT name,email FROM users WHERE id = ?",2)
get multi-rows data:
rows,err := mysqldb.GetResults("SELECT name,email FROM users where type = ?","public")
If you do not want to expose the database field name,you can set field name:
mysql.SetFields([]string{"username", "useremail"})
row,err := mysqldb.GetRow("SELECT name,email FROM users WHERE id = ?",2)
or
mysql.SetFields([]string{"username", "useremail"})
rows,err := mysqldb.GetResults("SELECT name,email FROM users where type = ?","public")
insert:
insertId, err := mysqldb.Insert( "insert into users set name = ?", "jim")
updata:
rowsAffected, err := mysqldb.Update( "update users set name = ? where id =?", "jim", 1)
delete:
rowsAffected, err := mysqldb.Delete( "delete from users where id =?", 453)
transaction:
tx,_:=mysqldb.TxBegin()
insertId, err := tx.Insert("insert into users set name = ?", "jim")
rowsAffected, err := tx.Update( "update users set name = ? where id =?", "jim", 1)
rowsAffected, err := tx.Delete( "delete from users where id =?", 453)
tx.Rollback()
or
tx.Commit()
debug: print last query
mysql.Debug()
print all errors
mysql.DebugMode()
mysql.Init("127.0.0.1", 3306, "dbname", "root", "123","utf8mb4", 100, 100)
mysqldb, err := mysql.Getmysqldb()
...
or
mysql.DebugMode()
mysqldb, err := mysql.Newmysqldb("127.0.0.1", 3306, "dbname", "root", "123","utf8mb4", 100, 100)
hide all errors
mysql.ReleaseMode()