问题:我正在使用 jackcess 创建记录并将其插入表中。我试图将重复记录插入表中,但我做不到。
有没有一种方法可以捕捉到有一个重复的条目试图添加,如果是的话,然后将一个额外的字符串连接到 PK 并使其唯一。在查询中检索操作时?
我目前使用以下代码插入数据库。
private static Database createDatabase(String databaseName) throws IOException {
return Database.create(new File(databaseName));
}
private static TableBuilder createTable(String tableName) {
return new TableBuilder(tableName);
}
public static void addColumn(Database database, TableBuilder tableName, String columnName, Types sqlType) throws SQLException, IOException {
tableName.addColumn(new ColumnBuilder(columnName).setSQLType(Types.INTEGER).toColumn()).toTable(database);
}
public static void startDatabaseProcess() throws IOException, SQLException {
String databaseName = "C:/Users/Alien/Documents/invited/employeedb.mdb"; // Creating an MS Access database
Database database = createDatabase(databaseName);
String tableName = "Employee"; // Creating table
Table table;
table = createTable(tableName)
.addColumn(new ColumnBuilder("Emp_Id").setSQLType(Types.INTEGER).toColumn())
.addColumn(new ColumnBuilder("Emp_Name").setSQLType(Types.VARCHAR).toColumn())
.addColumn(new ColumnBuilder("Emp_Employer").setSQLType(Types.VARCHAR).toColumn())
.toTable(database);
table.addRow(453456, "ilakkiaselvan","google");//Inserting values into the table
}
最佳答案
Is there is a way i can capture that there is an duplicate entry trying to be added if yes then concatenate an extra string to the PK and make it unique
如果您使用主键设置表,那么当您尝试添加主键已存在的行时,Jackcess 将引发异常。您的异常处理程序 (catch
) 可以调整主键并继续尝试,直到插入成功。
在您的情况下,您已将 PK 定义为整数,因此“将额外的字符串连接到 PK 并使其唯一”有点麻烦,但如果您有一个字符串 PK,则代码非常简单:
import java.io.File;
import com.healthmarketscience.jackcess.*;
public class jackcessTest {
public static void main(String[] args) {
String newEmp_Id = "GT001"; // test data
String newEmp_Name = "Gord"; //
boolean insertedOK = false;
int counter = 1;
String insertEmp_Id = newEmp_Id;
try {
Table table = DatabaseBuilder.open(new File("C:\\__tmp\\employeedb.mdb")).getTable("Employee");
while (!insertedOK) {
try {
table.addRow(insertEmp_Id, newEmp_Name);
insertedOK = true;
System.out.println(String.format("New record inserted as %s", insertEmp_Id));
} catch (ConstraintViolationException e) {
insertEmp_Id = String.format("%s_copy%s", newEmp_Id, counter++);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
当在空表上运行时,它通常会添加行:
Emp_Id Emp_Name
----------- --------
GT001 Gord
如果您再次运行它,它会添加带有修改后的 key 的第二条记录:
Emp_Id Emp_Name
----------- --------
GT001 Gord
GT001_copy1 Gord
...再一次...
Emp_Id Emp_Name
----------- --------
GT001 Gord
GT001_copy1 Gord
GT001_copy2 Gord
...等等。
关于java - 将 "duplicate"记录插入 Access 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14590629/