示例#1
0
func InsertPost(title []byte, slug string, markdown []byte, html []byte, featured bool, isPage bool, published bool, image []byte, created_at time.Time, created_by int64) (int64, error) {

	status := "draft"
	if published {
		status = "published"
	}
	writeDB, err := readDB.Begin()
	if err != nil {
		writeDB.Rollback()
		return 0, err
	}
	var result sql.Result
	if published {
		result, err = writeDB.Exec(stmtInsertPost, nil, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), title, slug, markdown, html, featured, isPage, status, image, created_by, created_at, created_by, created_at, created_by, created_at, created_by)
	} else {
		result, err = writeDB.Exec(stmtInsertPost, nil, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), title, slug, markdown, html, featured, isPage, status, image, created_by, created_at, created_by, created_at, created_by, nil, nil)
	}
	if err != nil {
		writeDB.Rollback()
		return 0, err
	}
	postId, err := result.LastInsertId()
	if err != nil {
		writeDB.Rollback()
		return 0, err
	}
	return postId, writeDB.Commit()
}
示例#2
0
文件: mysql551.go 项目: go51/mysql551
func (m *Mysql) Exec(query string, param ...interface{}) (rowsAffected int64, lastInsertId int64) {
	if !m.IsOpen() {
		panic(errors.New("[mysql555]It is not connected to the host"))
	}

	var res sql.Result = nil
	var err error = nil

	if m.IsTransaction() {
		res, err = m.tx.Exec(query, param...)
	} else {
		res, err = m.db.Exec(query, param...)
	}

	if err != nil {
		message := err.Error()
		message = message + "\n" + "[ SQL ] " + query + "\n" + fmt.Sprintf("[ PRM ] %#v\n", param)
		panic(errors.New(message))
	}

	lastInsertId, err = res.LastInsertId()
	if err != nil {
		panic(err)
	}
	rowsAffected, err = res.RowsAffected()
	if err != nil {
		panic(err)
	}

	return
}
示例#3
0
func (this *Config) Insert() error {
	this.Recordtime = getNow()
	var (
		err error
		id  int64
		res sql.Result
	)
	if this.Cat != nil {
		tran := this.Cat.NewTransaction(DBTITLE, "Config.Insert")
		defer func() {
			if err != nil {
				tran.SetStatus(err)
			} else {
				tran.SetStatus("0")
			}
			tran.Complete()
		}()
	}
	o := orm.NewOrm()
	res, err = o.Raw("INSERT INTO config(channelCode,`key`,value,recordTime)VALUES(?,?,?,?)", this.ChannelCode, this.Key, this.Value, this.Recordtime).Exec()
	if err != nil {
		return err
	}
	id, err = res.LastInsertId()
	if err != nil {
		return err
	}
	this.Id = id
	return nil
}
示例#4
0
func (a *Account) Save() error {
	db, err := connect()
	if err != nil {
		return err
	}
	defer db.Close()

	stmt, err := db.Prepare("insert or replace into T_ACCOUNTS (ID, NAME, EMAIL, PASSWORD, SALT, ROLE, LAST_AUTH) values (?,?,?,?,?,?,?)")
	if err != nil {
		return err
	}
	defer stmt.Close()

	var result sql.Result
	if a.Id < 1 {
		result, err = stmt.Exec(nil, a.Name, a.Email, a.Password, a.Salt, a.Role, a.LastAuth)
	} else {
		result, err = stmt.Exec(a.Id, a.Name, a.Email, a.Password, a.Salt, a.Role, a.LastAuth)
	}
	if err != nil {
		return err
	}

	id, err := result.LastInsertId()
	if err != nil {
		return err
	}
	a.Id = int(id)

	return nil
}
示例#5
0
文件: mysql.go 项目: lucmichalski/fae
func (this *mysql) Exec(query string, args ...interface{}) (afftectedRows int64,
	lastInsertId int64, err error) {
	if this.db == nil {
		return 0, 0, ErrNotOpen
	}
	if this.breaker.Open() {
		return 0, 0, ErrCircuitOpen
	}

	var result sql.Result
	result, err = this.db.Exec(query, args...)
	if err != nil {
		if this.isSystemError(err) {
			log.Warn("mysql exec breaks: %s", err.Error())
			this.breaker.Fail()
		}

		return 0, 0, err
	}

	afftectedRows, err = result.RowsAffected()
	if err != nil {
		if this.isSystemError(err) {
			log.Warn("mysql exec2 breaks: %s", err.Error())
			this.breaker.Fail()
		}
	} else {
		this.breaker.Succeed()
	}

	lastInsertId, _ = result.LastInsertId()
	return
}
示例#6
0
// task.ID will be ignored.
func CreateTask(task icarus.TaskData) (ID int, err error) {
	InitStorage()
	var res sql.Result
	res, err = db.Exec("INSERT INTO task (handle) VALUES (?)", task.Handle)
	if err != nil {
		log.Warnf("storage.CreateTask(): Failed to insert task %v: %s.", task, err.Error())
		return
	}
	newID, err := res.LastInsertId()
	if err != nil {
		log.Warnf("storage.CreateTask(): Failed to get ID for task %v: %s.", task, err.Error())
	}
	ID = int(newID)

	_, err = db.Exec("INSERT INTO user (userid, password, task_id) VALUES (?, ?, ?)", task.User.UserID, task.User.Password, ID)
	if err != nil {
		log.Warnf("storage.CreateTask(): Failed to insert user for task %v: %s.", task, err.Error())
		return
	}

	for _, c := range task.Courses {
		_, err = db.Exec("INSERT INTO course (name, desc, token, task_id) VALUES (?, ?, ?, ?)", c.Name, c.Desc, c.Token, ID)
		if err != nil {
			log.Warnf("storage.CreateTask(): Failed to insert course %v for task %v: %s.", c, task, err.Error())
			return
		}
	}

	return
}
示例#7
0
// POST /api/users
func (mgr *Manager) AddUser(w http.ResponseWriter, r *http.Request, rnd render.Render) {
	req := make(map[string]string)
	err := json.NewDecoder(r.Body).Decode(&req)
	if err != nil || len(req["name"]) < 3 || len(req["password"]) < 3 {
		w.WriteHeader(400)
		return
	}
	passwd, err := bcrypt.GenerateFromPassword([]byte(req["password"]), 11)
	if err != nil {
		log.Error("bcrypt.GenerateFromPassword: "******"insert into users (name, password) values(?,?)", req["name"], passwd)
	if err == nil {
		id, err = result.LastInsertId()
	}
	if err != nil {
		mgr.showError(err, w)
		return
	}
	rnd.JSON(200, map[string]interface{}{"name": req["name"], "id": id})
}
示例#8
0
文件: mysql.go 项目: zhuharev/storm
func (self *MysqlDriver) Create(container string, query driver.Query) (id interface{}, requestError error) {
	fmt.Println("mysql driver create:", container, query)
	// Create mysql insert string from given query
	var (
		queryFields []string
		queryValues []string
	)
	for k, v := range query {
		fmt.Println("key/value:", k, v)
		// TODO: check for sql injection
		queryFields = append(queryFields, k)
		queryValues = append(queryValues, fmt.Sprintf("'%s'", v))
	}
	fmt.Println("fields:", queryFields)
	fmt.Println("values:", queryValues)
	var result sql.Result
	if result, requestError = self.db.Exec(fmt.Sprintf("INSERT INTO `users`(%s) VALUES(%s)", strings.Join(queryFields, ","), strings.Join(queryValues, ","))); requestError != nil {
		// Failure
		return
	} else {
		// Success
		if id, requestError = result.LastInsertId(); requestError != nil {
			// Failure
			return
		}
	}
	// Success
	fmt.Println("success?:", id, requestError)
	return
}
示例#9
0
func NewOrUpdateUser(db *sql.DB, user *User) error {
	var err error
	var res sql.Result
	if user.Id == "" {
		res, err = db.Exec("INSERT INTO users(firstName, lastName) VALUES(?,?)", user.FirstName, user.LastName)
	} else {
		res, err = db.Exec("UPDATE users SET firstName=?, lastName=? WHERE id=?", user.FirstName, user.LastName, user.Id)
	}
	if err != nil {
		return err
	}
	lastId, err := res.LastInsertId()
	if err != nil {
		return err
	}
	rowCnt, err := res.RowsAffected()
	if err != nil {
		return err
	}
	if rowCnt != 1 {
		return errors.New(fmt.Sprintf("Row count (%s) and/or lastId (%s) are wrong.", lastId, rowCnt))
	}

	return nil
}
示例#10
0
// Execute an sql 'exec' that returns 'insert ids' (api is stupid)
func (self *sql) exec(query string, columns []string, values ...[]interface{}) (*rowset, error) {
	var output gsql.Result = nil
	var err error = nil

	// Pass params over
	if len(values) > 0 {
		output, err = self.db.Exec(query, values[0]...)
	} else {
		output, err = self.db.Exec(query)
	}
	if err != nil {
		return nil, utils.Fail(1, "Error perfroming explicit SQL query \"%s\": %s", query, err.Error())
	}

	// Process output
	var rtn = newRowset(nil).(*rowset)
	var id, id_err = output.LastInsertId()
	if id_err == nil {
		var record = map[string]interface{}{}
		for _, c := range columns {
			record[c] = id
		}
		rtn.Values.PushBack(record)
	}

	return rtn, err
}
示例#11
0
/**
 * Insert / convert ""/'' maybe a bug.
 * @param map of data
 * @return id,err
 */
func (this *Sql) Add(data map[string]interface{}) (int64, error) {
	var columns []string
	var values []string
	for k, v := range data {
		columns = append(columns, k)
		tmp_v := this.convertValue2String(v)
		values = append(values, "\""+tmp_v+"\"")
	}
	sqlstr := " INSERT INTO `" + this.tableName + "` " + " (" + strings.Join(columns, ",") + ") VALUES (" + strings.Join(values, ",") + ") "
	//slimSqlLog("Insert", sqlstr)
	var r sql.Result
	var err error
	if this.tx != nil {
		r, err = this.tx.Exec(sqlstr)
	} else {
		r, err = this.getDbW().Exec(sqlstr)
	}
	if err != nil {
		slimSqlLog("ERROR", sqlstr)
		return 0, err
	} else {
		id, err := r.LastInsertId()
		if err != nil {
			return 0, err
		} else {
			return id, nil
		}
	}
}
示例#12
0
func registerMembers() (err error) {
	members := []Member{
		{Name: "ミク", Birthday: "10/19", Bloodtype: "AB", Hobby: "ショッピング"},
		{Name: "マホ", Birthday: "1/8", Bloodtype: "AB", Hobby: "漫画"},
		{Name: "コヒメ", Birthday: "11/24", Bloodtype: "O", Hobby: "ゲーム"},
	}

	stmt, err := Db.Prepare(`
		INSERT INTO member (name, birthday, blood_type, hobby) 
		VALUES (?, ?, ?, ?)
	`)
	if err != nil {
		return
	}
	defer stmt.Close()

	for _, m := range members {
		var ret sql.Result
		ret, err = stmt.Exec(m.Name, m.Birthday, m.Bloodtype, m.Hobby)
		if err != nil {
			return
		}

		var id int64
		id, err = ret.LastInsertId()
		if err != nil {
			return
		}
		m.Id = int(id)
		fmt.Printf("Inserted. ID = %d, Name = %s\n", m.Id, m.Name)
	}

	return
}
示例#13
0
func (dbSeq *SequenceDB) NextSequence() (sequence uint64, err error) {
	var stmt *sql.Stmt
	stmt, err = dbSeq.db.Prepare(`REPLACE INTO sequence(stub) VALUES ("sequence")`)
	if err != nil {
		log.Printf("sequence db prepare error. %v", err)
		return 0, err
	}
	defer stmt.Close()

	var res sql.Result
	res, err = stmt.Exec()
	if err != nil {
		log.Printf("sequence db replace into error. %v", err)
		return 0, err
	}

	// 兼容LastInsertId方法的返回值
	var lastID int64
	lastID, err = res.LastInsertId()
	if err != nil {
		log.Printf("sequence db get LastInsertId error. %v", err)
		return 0, err
	} else {
		sequence = uint64(lastID)
		// mysql sequence will start at 1, we actually want it to be
		// started at 0. :)
		sequence -= 1
		return sequence, nil
	}
}
示例#14
0
func (h *Host) hostRowFromSqlResult(tx *sqlx.Tx, sqlResult sql.Result) (*HostRow, error) {
	hostId, err := sqlResult.LastInsertId()
	if err != nil {
		return nil, err
	}

	return h.GetByID(tx, hostId)
}
示例#15
0
func (sq *SavedQuery) savedQueryRowFromSqlResult(tx *sqlx.Tx, sqlResult sql.Result) (*SavedQueryRow, error) {
	savedQueryId, err := sqlResult.LastInsertId()
	if err != nil {
		return nil, err
	}

	return sq.GetByID(tx, savedQueryId)
}
示例#16
0
func (a *Cluster) clusterRowFromSqlResult(tx *sqlx.Tx, sqlResult sql.Result) (*ClusterRow, error) {
	applicationId, err := sqlResult.LastInsertId()
	if err != nil {
		return nil, err
	}

	return a.GetById(tx, applicationId)
}
示例#17
0
func (t *AccessToken) tokenRowFromSqlResult(tx *sqlx.Tx, sqlResult sql.Result) (*AccessTokenRow, error) {
	tokenId, err := sqlResult.LastInsertId()
	if err != nil {
		return nil, err
	}

	return t.GetByID(tx, tokenId)
}
示例#18
0
func (u *User) userRowFromSqlResult(tx *sqlx.Tx, sqlResult sql.Result) (*UserRow, error) {
	userId, err := sqlResult.LastInsertId()
	if err != nil {
		return nil, err
	}

	return u.GetById(tx, userId)
}
示例#19
0
文件: product.go 项目: heynickc/fpc
func (p *Product) productRowFromResult(tx *sqlx.Tx, sqlResult sql.Result) (*ProductRow, error) {
	productId, err := sqlResult.LastInsertId()
	if err != nil {
		return nil, err
	}

	return p.GetById(tx, productId)
}
示例#20
0
// Insert inserts the entity to a DB
func (d *Driver) Insert(object entities.Entity) (id int64, err error) {
	value, tableName, err := getTypeData(object)

	if err != nil {
		return 0, err
	}

	fieldsCount := value.NumField()
	var fieldNames []string
	var fieldValues []string

	for i := 0; i < fieldsCount; i++ {
		field := value.Field(i)
		tag := field.Tag.Get("db")
		if tag == "" {
			continue
		}
		fieldNames = append(fieldNames, tag)
		fieldValues = append(fieldValues, ":"+tag)
	}

	query := "INSERT INTO " + tableName + " (" + strings.Join(fieldNames, ", ") + ") VALUES (" + strings.Join(fieldValues, ", ") + ");"

	var result sql.Result
	switch object := object.(type) {
	case *entities.AuthorizedTransaction:
		result, err = d.database.NamedExec(query, object)
	case *entities.AllowedFi:
		result, err = d.database.NamedExec(query, object)
	case *entities.AllowedUser:
		result, err = d.database.NamedExec(query, object)
	case *entities.SentTransaction:
		result, err = d.database.NamedExec(query, object)
	case *entities.ReceivedPayment:
		result, err = d.database.NamedExec(query, object)
	}

	if err != nil {
		return
	}

	id, err = result.LastInsertId()

	if id == 0 {
		// Not autoincrement
		if object.GetID() == nil {
			return 0, fmt.Errorf("Not autoincrement but ID nil")
		}
		id = *object.GetID()
	}

	if err == nil {
		object.SetID(id)
		object.SetExists()
	}

	return
}
示例#21
0
func checkResult(c *C, r sql.Result, affectedRows int64, insertID int64) {
	gotRows, err := r.RowsAffected()
	c.Assert(err, IsNil)
	c.Assert(gotRows, Equals, affectedRows)

	gotID, err := r.LastInsertId()
	c.Assert(err, IsNil)
	c.Assert(gotID, Equals, insertID)
}
示例#22
0
文件: params.go 项目: hujunlong/orm
func (self *Params) Save() (bool, int64, error) {
	db, query := self.getWriteConnect()
	defer func() {
		self.set = self.set[len(self.set):]
	}()
	var err error
	var stmt *sql.Stmt
	var res sql.Result
	//var n int64
	//if n , err= self.Count();err == nil && n >0
	if self.hasRow {
		sqls, val := query.Update()
		if OpenSyncUpdate {
			sqls = strings.Replace(sqls, "?", "%v", -1)
			sqls = fmt.Sprintf(sqls, val...)
			SqlSyncHook <- sqls
			return false, 0, nil
		} else {
			if debug_sql {
				Debug.Println("save update ", sqls, val)
			}
			stmt, err = db.Prepare(sqls)
			if err == nil {
				defer stmt.Close()
			} else {
				return false, 0, err
			}
			res, err = stmt.Exec(val...)

			if err != nil {
				return false, 0, err
			}
			a, b := res.RowsAffected()
			return false, a, b
		}
	} else {
		sqls, val := query.Insert()
		if debug_sql {
			Debug.Println("save insert ", sqls, val)
		}
		stmt, err = db.Prepare(sqls)
		if err == nil {
			defer stmt.Close()
		} else {
			return false, 0, err
		}
		res, err = stmt.Exec(val...)
		if err != nil {
			return true, 0, err
		}
		a, b := res.LastInsertId()
		self.hasRow = true
		return true, a, b
	}

}
示例#23
0
文件: dao.go 项目: goatcms/goat-core
// Insert store given articles to database
func (dao *BaseDAO) Insert(tx db.TX, entity interface{}) (int64, error) {
	var (
		res sql.Result
		err error
	)
	if res, err = tx.NamedExec(dao.Table.insertSQL, entity); err != nil {
		return 0, err
	}
	return res.LastInsertId()
}
示例#24
0
func (library *Library) Flush() (err error) {
	var (
		tx     *sql.Tx
		stmt1  *sql.Stmt
		stmt2  *sql.Stmt
		res    sql.Result
		lastId int64
	)

	tx, err = library.db.Begin()
	if err != nil {
		return
	}

	stmt1, err = tx.Prepare("INSERT INTO songs (path, title, artist, albumartist, album, track, year, genre, composer, copyright) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
	if err != nil {
		tx.Rollback()
		return
	}

	stmt2, err = tx.Prepare("INSERT INTO comments (data, song_id) VALUES (?, ?)")
	if err != nil {
		tx.Rollback()
		return
	}

	for _, song := range library.queue {
		res, err = stmt1.Exec(song.Path, song.Title, song.Artist, song.AlbumArtist, song.Album, song.Track, song.Year, song.Genre, song.Composer, song.Copyright)
		if err != nil {
			tx.Rollback()
			return
		}

		if len(song.Comments) > 0 {
			lastId, err = res.LastInsertId()
			if err != nil {
				tx.Rollback()
				return
			}

			for _, comment := range song.Comments {
				_, err = stmt2.Exec(comment, lastId)
				if err != nil {
					tx.Rollback()
					return
				}
			}
		}
	}

	err = tx.Commit()
	library.queue = nil
	return
}
示例#25
0
文件: main.go 项目: mattn/go-sqlite3
func resultDoCheck(result sql.Result, callerDescr string, callIndex int) {
	lastID, err := result.LastInsertId()
	if err != nil {
		log.Panic(err)
	}
	nAffected, err := result.RowsAffected()
	if err != nil {
		log.Panic(err)
	}

	log.Printf("Exec result for %s (%d): ID = %d, affected = %d\n", callerDescr, callIndex, lastID, nAffected)
}
示例#26
0
//根据主键删除一条数据,返回所影响的行
func (this *MyDb) Delete(model interface{}) (int64, error) {
	strSql, param, _, err := generateDeleteSql(model)
	if err != nil {
		return 0, err
	}
	var result sql.Result
	result, err = this.Exec(strSql, param...)
	if err != nil {
		return 0, err
	}
	var effect int64
	effect, err = result.LastInsertId()
	return effect, err
}
示例#27
0
/**
 * [modifyData description]
 * @param  {[type]} db *sql.DB       [description]
 * @return {[type]}    [description]
 */
func modifyData(db *sql.DB) {
	var stmt *sql.Stmt
	var res sql.Result

	stmt, err := db.Prepare("INSERT INTO company(name, address) VALUES ($1,$2)")
	checkErr(err)

	res, err = stmt.Exec("Carnevale Interactive", "Grand Rapids MI")
	checkErr(err)

	lastId, err := res.LastInsertId()
	checkErr(err)
	log.Println(lastId)
}
func (maker *courseMaker) Create(course *Course) error {

	var (
		err                 error
		courseQuery         = queries["create_course"]
		courseMemberQuery   = queries["create_course_members"]
		courseTeachersQuery = queries["create_course_teachers"]
		acid                util.AcidTx
		result              sql.Result
		stmt                *sqlx.Stmt
	)

	acid = func(tx *sqlx.Tx) {
		// Add the course
		stmt, err = tx.Preparex(courseQuery)
		if err != nil {
			panic(err)
		}
		if result, err = stmt.Exec(course.Name); err != nil {
			panic(err)
		}
		course.ID, err = result.LastInsertId()
		if err != nil {
			panic(err)
		}

		// Then add a new record for each of the students to course_members
		for _, student := range course.Students {
			stmt, err = tx.Preparex(courseMemberQuery)
			if err != nil {
				panic(err)
			}
			if result, err = stmt.Exec(course.ID, student.ID); err != nil {
				panic(err)
			}
		}

		// Then add a new record for each of the teachers to course_teachers
		for _, teacher := range course.Teachers {
			stmt, err = tx.Preparex(courseTeachersQuery)
			if err != nil {
				panic(err)
			}
			if result, err = stmt.Exec(course.ID, teacher.ID); err != nil {
				panic(err)
			}
		}
	}
	return util.AcidCtx(acid, maker)
}
示例#29
0
文件: post.go 项目: hjin-me/HJinBlog
func (p *RawPost) Save() error {
	db, err := da.Connect()
	if err != nil {
		return err
	}
	var (
		stmt     *sql.Stmt
		isInsert = false
	)
	var (
		result sql.Result
	)
	if p.Id == 0 {
		// "INSERT INTO " + TABLE_NAME_POSTS + "(uid, content, cid, pubtime, title, description, keywords) VALUES (?,?,?,?,?,?,?)"
		// "UPDATE " + TABLE_NAME_POSTS + " SET content=?, cid=?, pubtime=?, title=?, description=?, keywords=? WHERE id=?"
		stmt, err = db.Prepare(INSERT_POSTS) // ? = placeholder
		if err != nil {
			return err
		}
		isInsert = true
		defer stmt.Close() // Close the statement when we leave main() / the program terminates
		result, err = stmt.Exec(p.UserId, string(p.Content), p.Category.Id, p.PubTime.Unix(), p.Title, p.Description, p.Keywords.String())
		if err != nil {
			return err
		}
	} else {
		stmt, err = db.Prepare(UPDATE_POSTS) // ? = placeholder
		if err != nil {
			return err
		}
		defer stmt.Close() // Close the statement when we leave main() / the program terminates
		result, err = stmt.Exec(string(p.Content), p.Category.Id, p.PubTime.Unix(), p.Title, p.Description, p.Keywords.String(), p.Id)
		if err != nil {
			return err
		}
	}

	if isInsert {
		id, err := result.LastInsertId()
		if err != nil {
			return err
		}
		p.Id = int(id)
	}
	return nil

	// Prepare statement for inserting data
	// db.Do("hmset", "post:"+p.Id, "id", p.Id, "title", p.Title, "content", string(p.Content), "keywords", p.Keywords.Marshal(), "description", p.Description, "pubtime", p.PubTime.Unix(), "category", p.Category)
}
示例#30
-2
// Insert 向指定table插入数据
func (this *builder) Insert(table string, model interface{}) int {
	query := "insert into `" + table + "`"
	value := reflect.ValueOf(model).Elem()
	data := make(map[string]interface{})
	mapStructToMap(value, data)
	keys := " ("
	values := " ("
	params := make([]interface{}, 0, 0)
	for k, v := range data {
		keys += "`" + k + "`,"
		values += "?,"
		params = append(params, v)
	}
	query += keys[:len(keys)-1] + ") values"
	query += values[:len(values)-1] + ")"
	var result sql.Result
	var err error
	this.reset()
	result, err = this.db.Exec(query, params...)
	if err != nil {
		return -1
	}
	var id int64
	id, err = result.LastInsertId()
	if err != nil {
		return -1
	}
	return int(id)
}