項(xiàng)目高并發(fā)的時(shí)候很容易出現(xiàn)數(shù)據(jù)庫(kù)插入相同的數(shù)據(jù),雖然可以使用唯一索引避免插入相同數(shù)據(jù),但是不斷的程序報(bào)錯(cuò)也是我們要避免的。
MySQL中的插入更新
使用 insert ... on duplicate key update .. 語(yǔ)法可以避免上述情況,舉個(gè)例子
drop table if exists `test`;
create table `test` (
`id` int(11) not null AUTO_INCREMENT,
`name` varchar(32) not null default '',
`update_ts` timestamp not null default current_timestamp(),
primary key (`id`)
) engine=InnoDB default charset=utf8mb4;
主鍵 id 是天然的唯一索引,我們插入重復(fù)數(shù)據(jù)時(shí)會(huì)報(bào)錯(cuò)
> INSERT INTO test (id, name) VALUES (1, 'wxnacy');
> INSERT INTO test (id, name) VALUES (1, 'wxnacy');
Error 1062: Duplicate entry '1' for key 'PRIMARY'
查看插入的數(shù)據(jù)
> SELECT * FROM `test`;
| id | name | update_ts |
|------------------------------------
| 1 | wxnacy | 2019-05-16 22:26:58 |
下面我們來?yè)Q個(gè)語(yǔ)句
> insert into test (id, name) values (1, 'wxnacy') on duplicate key update update_ts = current_timestamp();
> SELECT * FROM `test`;
+----+--------+---------------------+
| id | name | update_ts |
+----+--------+---------------------+
| 1 | wxnacy | 2019-05-16 22:39:49 |
+----+--------+---------------------+
on duplicate key update 前面是正常的插入語(yǔ)句,其后跟著的是當(dāng)唯一索引沖突時(shí),想要更新的數(shù)據(jù)。
再換個(gè)使用場(chǎng)景,如果我想讓數(shù)據(jù)庫(kù)中用戶名是唯一的,則可以先建立唯一索引,在使用該語(yǔ)法。
> alter table test add unique index_name (name);
> insert into test (name) values ('wenn') on duplicate key update update_ts = current_timestamp();
> SELECT * FROM `test`;
+----+--------+---------------------+
| id | name | update_ts |
+----+--------+---------------------+
| 1 | wxnacy | 2019-05-16 22:49:29 |
| 2 | wenn | 2019-05-16 22:49:49 |
+----+--------+---------------------+
> insert into test (name) values ('wenn') on duplicate key update update_ts = current_timestamp();
> SELECT * FROM `test`;
+----+--------+---------------------+
| id | name | update_ts |
+----+--------+---------------------+
| 1 | wxnacy | 2019-05-16 23:09:12 |
| 2 | wenn | 2019-05-16 23:11:42 |
+----+--------+---------------------+
這樣及保證了避免插入重復(fù)數(shù)據(jù),同時(shí)程序也沒有報(bào)錯(cuò),我還可以根據(jù) update 的數(shù)據(jù)來分析問題的根源。
SQLAlchemy 中的存在即更新
如果你有興趣 可以看下官方文檔 INSERT…ON DUPLICATE KEY UPDATE (Upsert)
我們看先下官方文檔的實(shí)例代碼
from sqlalchemy.dialects.mysql import insert
insert_stmt = insert(my_table).values(
id='some_existing_id',
data='inserted value')
on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
data=insert_stmt.inserted.data,
status='U'
)
conn.execute(on_duplicate_key_stmt)
上面代碼的意思是 當(dāng)你有一個(gè)已經(jīng)存在的主鍵some_existing_id的時(shí)候,你去執(zhí)行上面的插入操作的時(shí)候 將會(huì)執(zhí)行下面的對(duì)應(yīng)主鍵的更新操作。
官方代碼總是很抽象,我們來個(gè)實(shí)際的例子吧。
from sqlalchemy.dialects.mysql import insert
db_client = get_db_client()
insert_stmt = insert(table_sa).values(**data)
on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
**data
)
await db_client.execute(on_duplicate_key_stmt)
上個(gè)代碼其中的data是一個(gè)字典,其中的key是數(shù)據(jù)庫(kù)對(duì)用的字段。意思是當(dāng)我插入到數(shù)據(jù)中的時(shí)候,當(dāng)存在重復(fù)的唯一鍵的時(shí)候,將會(huì)直接更新數(shù)據(jù)。
注意:想要使用上面的方法,我們需要?jiǎng)?chuàng)建一個(gè)唯一索引(即使是聯(lián)合唯一索引也行)