现在的位置: 首页 > 综合 > 正文

android sqlite 不存在插入,存在更新语句

2018年04月05日 ⁄ 综合 ⁄ 共 728字 ⁄ 字号 评论关闭

1.表不存在则创建

create table  if not exists student( _id Integer primary key autoincrement , name Text , age Integer)

2.当表中的数据不存在时插入数据

insert into student(name,age) select 'zz7zz7zz',25 where not exists(select * from student where name='zz7zz7zz' and age=25)

重复执行多次,仍然只有一条数据

3.当表中的数据不存在则插入,存在则更新 (使用REPLACE  语句)

这时候的创建表的sql语句为:create table  if not exists student( _id Integer primary key , name Text , age Integer)

不存在插入,存在更新sql语句为:replace into student( _id , name ,age ) VALUES ( 1,'zz7zz7zz',25) ,重复执行多次,仍然只有一条数据

将年龄改为35,发现数据表没有插入新数据,只是更新了

replace into student( _id , name ,age ) VALUES ( 1,'zz7zz7zz',35)

将学生id(主键)改为2,则发现插入了一条新数据

replace into student( _id , name ,age ) VALUES ( 2,'zz7zz7zz',35)

引用文章:http://www.cnblogs.com/liping13599168/archive/2011/05/24/2054908.html

邮箱:zz7zz7zz@163.com

微博http://weibo.com/u/3209971935

抱歉!评论已关闭.