浏览代码

初始化

wangchuanjin 5 年之前
父节点
当前提交
422ce6b54b
共有 1 个文件被更改,包括 26 次插入2 次删除
  1. 26 2
      src/mysql/mysql.go

+ 26 - 2
src/mysql/mysql.go

@@ -88,6 +88,16 @@ func (m *Mysql) InsertBySqlByTx(tx *sql.Tx, sql string, args ...interface{}) int
 	return id
 }
 
+//批量新增
+func (m *Mysql) InsertIgnoreBatch(tableName string, fields []string, values []interface{}) (int64, int64) {
+	return m.InsertIgnoreBatchByTx(nil, tableName, fields, values)
+}
+
+//带事务的批量新增
+func (m *Mysql) InsertIgnoreBatchByTx(tx *sql.Tx, tableName string, fields []string, values []interface{}) (int64, int64) {
+	return m.insertOrReplaceBatchByTx(tx, "INSERT", "IGNORE", tableName, fields, values)
+}
+
 //批量新增
 func (m *Mysql) InsertBatch(tableName string, fields []string, values []interface{}) (int64, int64) {
 	return m.InsertBatchByTx(nil, tableName, fields, values)
@@ -95,6 +105,20 @@ func (m *Mysql) InsertBatch(tableName string, fields []string, values []interfac
 
 //带事务的批量新增
 func (m *Mysql) InsertBatchByTx(tx *sql.Tx, tableName string, fields []string, values []interface{}) (int64, int64) {
+	return m.insertOrReplaceBatchByTx(tx, "INSERT", "", tableName, fields, values)
+}
+
+//批量更新
+func (m *Mysql) ReplaceBatch(tableName string, fields []string, values []interface{}) (int64, int64) {
+	return m.InsertBatchByTx(nil, tableName, fields, values)
+}
+
+//带事务的批量更新
+func (m *Mysql) ReplaceBatchByTx(tx *sql.Tx, tableName string, fields []string, values []interface{}) (int64, int64) {
+	return m.insertOrReplaceBatchByTx(tx, "REPLACE", "", tableName, fields, values)
+}
+
+func (m *Mysql) insertOrReplaceBatchByTx(tx *sql.Tx, tp string, afterInsert, tableName string, fields []string, values []interface{}) (int64, int64) {
 	placeholders := []string{}
 	for range fields {
 		placeholders = append(placeholders, "?")
@@ -104,7 +128,7 @@ func (m *Mysql) InsertBatchByTx(tx *sql.Tx, tableName string, fields []string, v
 	for i := 0; i < len(values)/len(fields); i++ {
 		array = append(array, fmt.Sprintf("(%s)", placeholder))
 	}
-	q := fmt.Sprintf("INSERT INTO %s (%s) VALUES %s", tableName, strings.Join(fields, ","), strings.Join(array, ","))
+	q := fmt.Sprintf("%s %s INTO %s (%s) VALUES %s", tp, afterInsert, tableName, strings.Join(fields, ","), strings.Join(array, ","))
 	result, _ := m.ExecBySqlByTx(tx, q, values...)
 	if result == nil {
 		return -1, -1
@@ -299,7 +323,7 @@ func (m *Mysql) UpdateByTx(tx *sql.Tx, tableName string, query, update map[strin
 	}
 	q := fmt.Sprintf("update %s set %s where %s", tableName, strings.Join(q_fs, ","), strings.Join(u_fs, " and "))
 	log.Println(q, values)
-	return m.UpdateOrDeleteBySqlByTx(tx, q, values...) > 0
+	return m.UpdateOrDeleteBySqlByTx(tx, q, values...) >= 0
 }
 
 //删除