【问题标题】:Jackcess get a sorted table or biggest index in itJackcess 在其中获取排序表或最大索引
【发布时间】:2013-01-24 16:36:43
【问题描述】:

我想在这样创建的 jackcess 表中插入一行;

Table t = Database.open(new File(dbUrl)).getTable(tname);

通常,如果我使用 SQL,这将是对它进行排序的正确时间。尽管如此,我还是查看了文档,并没有发现任何内容。

无论如何,在拿到表格后,我尝试通过使用在其中插入一行;

        int id = t.getRowCount() + 1;

        try {
            t.addRow(id, "MyName", "MyLastName");
        } catch (IOException ex) {
            ex.printStackTrace();
        }

但是,由于索引没有排序,我得到以下异常;

java.io.IOException: New row [250, MyName, MyLastName, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null] violates uniqueness constraint for index 
Data number: 5
Page number: 99
Is Backing Primary Key: true
Is Unique: true
Ignore Nulls: false
Columns: [ColumnDescriptor  Name: (CLIENTES) ID_CLIENTE
Type: 0x4 (LONG)
Number: 0
Length: 4
Variable length: false flags: 1]
Initialized: true
EntryCount: 249
    Cache: 
    LeafDataPage[99] 0, 0, (0), [RowId = 93:0, Bytes = 7F 80 00 00  00 , RowId = 6844:0, Bytes = 7F 80 00 01  5C]

at com.healthmarketscience.jackcess.IndexData.addEntry(IndexData.java:571)
at com.healthmarketscience.jackcess.IndexData.addRow(IndexData.java:537)
...

现在,我认为它可能由于缺少其他列而失败,但后来我尝试使用 t.getRowCount() + 100; 并且能够插入。所以我的问题显然是我不知道如何获取索引或排序表。

显然,计算行数是一个糟糕的解决方案。反正我也试过了。

【问题讨论】:

    标签: java ms-access insert indexing jackcess


    【解决方案1】:

    要按排序顺序检索行,您可以遍历由索引支持的游标。以下代码使用答案here 中描述的技术,按主键顺序遍历表并检索最大的键值。然后它添加一个具有下一个最大键值的新行。

    import java.io.File;
    import java.io.IOException;
    import com.healthmarketscience.jackcess.*;
    
    public class jackcessTest {
    
        public static void main(String[] args) {
            try {
                Table table = DatabaseBuilder.open(new File("C:\\Users\\Public\\Database1.accdb")).getTable("JackcessTest");
                int LargestKey = 0;
                // the following loop is modified from 
                //     https://stackoverflow.com/a/19304549/2144390
                //     for Jackcess 2.0
                for(Row row : CursorBuilder.createCursor(table.getPrimaryKeyIndex())) {
                    LargestKey = (int)row.get("ID");
                }
                try {
                    table.addRow(LargestKey + 1, "MyName", "MyLastName");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Done.");        
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      • 2022-11-03
      • 2019-02-13
      • 1970-01-01
      相关资源
      最近更新 更多