How to ALTER TABLE using UCanAccess

我与影子孤独终老i 提交于 2019-11-29 17:25:15

UCanAccess versions 4.0.0 and above now support ALTER TABLE, e.g.,

Statement stmt = conn.createStatement();
stmt.execute("ALTER TABLE TableName ADD COLUMN newCol LONG");

Ucanaccess can't support this very requested feature until the underlying jackcess library doesn't support it. We (Ucanaccess team) could automate the above mentioned steps, but for the same reason, we can't create fk and so, in many cases, reproduce an exact copy of an original table. While altering a table, we would lose the referential integrity constraints... so, for now, it's better to do nothing. So sorry, no solution currently.

Update: January 2017

UCanAccess now supports ALTER TABLE. See my other answer to this question.


(Previous outdated answer.)

If your Java app is running under Windows then you can use the following workaround. It creates a little VBScript and invokes CSCRIPT.EXE to run it

String dbFileSpec = "C:\\Users\\Public\\mdbTest.mdb";

// write a temporary VBScript file ...
File vbsFile = File.createTempFile("AlterTable", ".vbs");
vbsFile.deleteOnExit();
PrintWriter pw = new PrintWriter(vbsFile);
pw.println("Set conn = CreateObject(\"ADODB.Connection\")");
pw.println("conn.Open \"Driver={Microsoft Access Driver (*.mdb)};Dbq=" + dbFileSpec + "\"");
pw.println("conn.Execute \"ALTER TABLE TEmployee ADD COLUMN NotificationsEnabled YESNO\"");
pw.println("conn.Close");
pw.println("Set conn = Nothing");
pw.close();

// ... and execute it
Process p = Runtime.getRuntime().exec("CSCRIPT.EXE \"" + vbsFile.getAbsolutePath() + "\"");
p.waitFor();
BufferedReader rdr = 
        new BufferedReader(new InputStreamReader(p.getErrorStream()));
int errorLines = 0;
String line = rdr.readLine();
while (line != null) {
    errorLines++;
    System.out.println(line);  // display error line(s), if any
    line = rdr.readLine();
}
if (errorLines == 0) {
    System.out.println("The operation completed successfully.");
}

Notes:

  1. The above code will work for updating an .mdb file if the Java app is running under a 32-bit JVM. If you need to update an .accdb file or if the Java app is running under a 64-bit JVM then the appropriate version of Microsoft's Access Database Engine (32-bit or 64-bit, same as the JVM) will have to be installed and you will need to use Driver={Microsoft Access Driver (*.mdb, *.accdb)}.

  2. This workaround uses ODBC but it does not use Java's JDBC-ODBC Bridge, so it will work with Java 8.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!