Java 使用同一查询插入多个值
在我的应用程序中,我经常需要在数据库的表中插入很多值 所以我需要运行一个插入,如:Java 使用同一查询插入多个值,java,android,sql,database,sqlite,Java,Android,Sql,Database,Sqlite,在我的应用程序中,我经常需要在数据库的表中插入很多值 所以我需要运行一个插入,如: insert into clients (id, name, lastip, visites) values ('20','John','1.1.1.1','0'), ('21','Kate','1.1.1.2','3'), ('35','Phill','1.1.1.3','90') ; 关于这一点,我有两个问题(我是SQL初学者) 如何避免主键崩溃(如果尝试插入现有行,则替换其他列) 是否有一种方法可
insert into clients
(id, name, lastip, visites) values
('20','John','1.1.1.1','0'),
('21','Kate','1.1.1.2','3'),
('35','Phill','1.1.1.3','90') ;
关于这一点,我有两个问题(我是SQL初学者)
id
将是一个自动递增字段,则无需在插入中指定它
2.)是的,这是可能的(一行),如您参考的文档所示:
public long insert (String table, String nullColumnHack, ContentValues values)
值此映射包含行的初始列值。这个
键应该是列名和列值
但是,您应该使用准备好的语句(此处引用:)
如果要一次插入所有3行,则需要构建字符串或执行3次插入
编辑您的评论:
3.)这在这里得到了很好的回答:
另见此处:
替换
当发生唯一约束冲突时,替换算法
删除导致约束冲突的预先存在的行
在插入或更新当前行和命令之前
继续正常执行。如果非空约束冲突
发生时,替换冲突解决方案将空值替换为
如果该列没有默认值,则输入该列的默认值
值,则使用中止算法。如果存在检查约束
发生冲突时,始终使用替换冲突解决算法
像中止一样工作
如果您正在使用
ContentProvider
访问数据库,则可以使用applyBatch()
:
//操作列表
ArrayList谢谢你的回答,我真的不想避免主键崩溃,我需要的是更新行(如果已经)exists@Adrmedi:我编辑我的帖子是为了在你的问题中加入更多信息
// List of operations
ArrayList<ContentProviderOperation) ops
= new ArrayList<ContentProviderOperation>();
// Create the builder
ContentProviderOperation.Builder builder
= ContentProviderOperation.newInsert(...);
// Create the first item
builder.withValue("Name", "John");
builder.withValue("IP", '1.1.1.1');
ops.add(builder.build());
// Create the second item
builder.withValue("Name", "Kate");
builder.withValue("IP", '1.1.1.2');
ops.add(builder.build());
// Insert the data as one transaction
getContentProvider().applyBatch("AUTHORITY", ops);