简体   繁体   English

SQLite使用泛型创建插入语句(Java + SQLite4Java)

[英]SQLite creating insert statement with generics (Java + SQLite4Java)

I am trying to make an insert command using java generics. 我正在尝试使用Java泛型进行插入命令。 Basically, I want to make my addrow() function type safe and usable for different tables. 基本上,我想使我的addrow()函数类型安全且可用于不同的表。 Is it possible? 可能吗?

Here is my current java code: 这是我当前的Java代码:

public <T extends List<D>, D extends Number> boolean addRow(T rowData) throws SQLiteException {
    int index = 0;
    for (D element : rowData) {
        addRowStatement.bind(index++, element); // element must have a type part and value part
    }
    return addRowStatement.step();
}

Where addRowStatement is of type SQLiteStatement and from what I understand, one can keep binding items to it. 根据我的理解,在addRowStatement类型为SQLiteStatement的情况下,可以将项目绑定到该对象。

The data within the ArrayList T will be either bytes, ints, or some primitive like this. ArrayList T中的数据将是字节,整数或类似的某种原语。 My code handles this. 我的代码处理了这个。 I just want to elegantly bind all the data (no matter how many things there are to bind) and execute the statements. 我只想优雅地绑定所有数据(无论要绑定多少东西)并执行语句。

Specifically, the error is the bind() method doesn't know what to do with the "D" generic -- even though the D generic will turn out to be an int or byte or something. 具体来说,错误是bind()方法不知道如何处理“ D”泛型-即使D泛型最终可能是int或byte或其他内容。

Eric, 埃里克

First of all, D cannot be int , it can only be java.lang.Integer . 首先, D不能为int ,只能为java.lang.Integer

Secondly, the compiler doesn't know the type at compile time so it doesn't know which bind to match the call to. 其次,编译器在编译时不知道类型,因此不知道匹配该调用的绑定 There's no generic bind in sqlite4java, unfortunately. 不幸的是,sqlite4java中没有通用绑定

Thirdly, due to erasure, the type of D is not known at runtime, you need to check it. 第三,由于擦除, D的类型在运行时未知,您需要检查它。

So the solution is: 因此解决方案是:

if (element == null) addRowStatement.bindNull(index++);
else if (element instanceof Integer) addRowStatement.bind(index++, (Integer)element);
else if (element instanceof Long) addRowStatement.bind(index++, (Long)element);
...
else throw new AssertionError("unsupported type " + element.getClass());

Or simpler, if you can go with converting every Number to long: 或更简单的是,如果可以将每个Number转换为long:

if (element == null) addRowStatement.bindNull(index++);
else addRowStatement.bind(index++, element.longValue());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM