问题
I am currently writing a mdb Migration script in Java. This is noting but adding and modifying some of the column names in the MDB file.
I created new tables and thats not a problem but I could not find a query to Alter the name of the column
Lets say I have table named Employees having columns as "ID", "EName", "Active?" Now I want to change the column name "Active?" to "Active" (i.e. without question mark.)
How this can be done using JDBC java. THanks
回答1:
One way to accomplish your goal would be to save the following VBScript code as RenameColumn.vbs
...
Option Explicit
Dim objArgs, dbPath, tblName, oldColName, newColName
Dim dbe ' As DAO.DBEngine
Dim db ' As DAO.Database
Dim fld ' As DAO.Field
Set objArgs = WScript.Arguments
dbPath = objArgs(0)
tblName = objArgs(1)
oldColName = objArgs(2)
newColName = objArgs(3)
Set dbe = CreateObject("DAO.DBEngine.120")
Set db = dbe.OpenDatabase(dbPath)
Set fld = db.TableDefs(tblName).Fields(oldColName)
fld.Name = newColName
Set fld = Nothing
Set db = Nothing
Set dbe = Nothing
...and then your Java program could invoke it using code something like this:
import java.io.*;
public class RenameColumns {
public static void main(String[] args) {
String dbPath = "C:\\__tmp\\Database1.accdb";
String tblName = "Employees";
String oldColName = "Active?";
String newColName = "Active";
String cmd =
"cscript C:\\__tmp\\RenameColumn.vbs"
+ " \"" + dbPath + "\""
+ " \"" + tblName + "\""
+ " \"" + oldColName + "\""
+ " \"" + newColName + "\"";
try {
Process p = Runtime.getRuntime().exec(cmd);
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.");
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
回答2:
Seems MS Access does not allow the renaming of the columns(reference links 1,2). Only way forward is,
- Backup your data in a different table
- Drop the column
- Add a column with new name
- Populate the table from the backed up table.
来源:https://stackoverflow.com/questions/17669720/changing-column-name-in-mdb-file-using-jdbc-java