importing data in tables error exception in mysql - java

I am making a program where I read data from .txt files and store them in tables. In my program the user would give the directory of the files, the program would find all the .txt files and for each one of these would create a table which would have as name the name of the file and each table would have two fields (text and price).
These two columns are separeted by space. In my code below is shown all the program. But I have problem when I am trying to import the data programmatically. The Error exception that I get is that I have error in SQL syntax. Could anyone help me because I am trying to solve it for a couple af days with no result?
public class notepad {
public static void main(String args[]) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection(
"jdbc:mysql://localhost:3330/mydb", "root", "root");
String dirpath = "";
Scanner scanner1 = new Scanner(System.in);
while (true) {
System.out.println("Please give the directory:");
dirpath = scanner1.nextLine();
File fl = new File(dirpath);
if (fl.canRead())
break;
System.out.println("Error:Directory does not exists");
}
try {
String files;
File folder = new File(dirpath);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
if (files.endsWith(".txt") || files.endsWith(".TXT")) {
List<File> txtFiles = new ArrayList<File>();
txtFiles.add(listOfFiles[i]);
String[] parts = files.split("\\.");
String tablename = parts[0];
for (File txtFile : txtFiles) {
List sheetData = new ArrayList();
try {
FileReader in = new FileReader(txtFile);
BufferedReader br = new BufferedReader(in);
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
String filename = dirpath.substring(dirpath
.indexOf('\\') - 2, files
.indexOf(parts[0]));
}
in.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
getCreateTable1(con, tablename);
importData(con, txtFile, tablename);
}
}
}
}
} catch (Exception e) {
System.out.println();
}
}
private static String getCreateTable1(Connection con, String tablename) {
try {
Class.forName("com.mysql.jdbc.Driver");
Statement stmt = con.createStatement();
String createtable = "CREATE TABLE " + tablename
+ " ( text VARCHAR(255), price int )";
System.out.println("Create a new table in the database");
stmt.executeUpdate(createtable);
} catch (Exception e) {
System.out.println(((SQLException) e).getSQLState());
System.out.println(e.getMessage());
e.printStackTrace();
}
return null;
}
private static String importData(Connection con, File txtFile,
String tablename) {
try {
Statement stmt;
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String importingdata = "LOAD DATA INFILE '"
+ txtFile.getAbsolutePath() + "' INTO TABLE '" + tablename
+ " (text,price)";
stmt.executeUpdate(importingdata);
} catch (Exception e) {
System.out.println(((SQLException) e).getSQLState());
System.out.println(e.getMessage());
e.printStackTrace();
}
return null;
}
}

Try change
+ txtFile.getAbsolutePath() + "' INTO TABLE '" + tablename
^
to
+ txtFile.getAbsolutePath() + "' INTO TABLE " + tablename
This orphan quote makes your statement invalid.

Related

Trying to read 700k+ of data and the Error "GC Overhead Limit Exceeded" occurred

Alright so I need help in reviewing my codes because I'm kinda still new in programming (currently in my second year of Diploma in Computer Science). I got this error as in the title GC Overhead Limit Exceeded when I tried running my code below.
A brief explanation of this code, I'm trying to read data from a CSV File and then transfer it to a database. FYI, there are actually 10 tables/CSV files that I need to read, but on this I'll show this one table Tickets because the error only occurred when I tried to read that table/file. The other tables have hundreds of rows/data only while the table Tickets have 735,504 of rows/data. Furthermore, I've succeeded in reading 450,028 of data after 6 hours of running the code before the error occurred.
What can I do to fix this error? What can be modified to improve my code? I really appreciate it if you guys can help me :)
public class Demo2 {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/database";
String username = "root";
String password = "password";
try {
//Connect to the database
Connection connection = DriverManager.getConnection(url, username, password);
//Test on one table only
String tableName = "Tickets";
System.out.println("Connecting to TABLE " +tableName +"...");
readCSVFile(tableName, connection);
System.out.println();
System.out.println("THE END");
connection.close();//close connection to the database
}
catch (SQLException e) {
System.out.println("ERROR at main(): SQLException!!");
e.printStackTrace();
}
}
static int countNewRow = 0;
static int countUpdatedRow = 0;
//Method to read the CSV File
static void readCSVFile(String tableName, Connection conn) {
//Read CSV File
try {
String path = tableName +".csv";
BufferedReader br = new BufferedReader(new FileReader(path));
br.readLine();//skip the first line
String inData;
//Read The Remaining Line
while((inData=br.readLine()) != null)
{
String[] rowData = inData.split(",");
ArrayList <String> rowDataList = new ArrayList<String>();
for (int i=0; i<rowData.length; i++)
rowDataList.add(rowData[i]);
//To combine String that starts and ends with "
for(int i=0; i<rowDataList.size(); i++) {
if (rowDataList.get(i).charAt(0) == '"') {
String string1 = rowDataList.get(i).substring(1, rowDataList.get(i).length());
String string2 = rowDataList.get(i+1).substring(0, rowDataList.get(i+1).length()-1);
String combined = string1 +"," +string2;
rowDataList.set(i, combined);
rowDataList.remove(i+1);
break;
}
}
//Remove the RM
for(int i=0; i<rowDataList.size(); i++) {
if (rowDataList.get(i).startsWith("RM")) {
String string = rowDataList.get(i).substring(2);
rowDataList.set(i, string);
}
}
//This is just to keep track of the data that has been read
System.out.println("[" +rowDataList.get(0) +"]");
//Transfer the data to the database
insertToDatabase(conn, tableName, rowDataList);
}
System.out.println("New Row Added : " +countNewRow);
System.out.println("Updated Row : " +countUpdatedRow);
System.out.println("== Process Completed ==");
br.close();
}
catch (FileNotFoundException e) {
System.out.println("ERROR at readCSVFile(): FileNotFoundException!!");
e.printStackTrace();
}
catch (IOException e) {
System.out.println("ERROR at readCSVFile(): IOException!!");
e.printStackTrace();
}
catch (SQLException e) {
System.out.println("ERROR at readCSVFile(): SQLException!!");
e.printStackTrace();
}
catch (ParseException e) {
System.out.println("ERROR at readCSVFile(): ParseException!!");
e.printStackTrace();
}
}
static void insertToDatabase(Connection connection, String tableName, ArrayList <String> rowDataList) throws SQLException, ParseException {
String tableIdName = tableName;
if (tableIdName.charAt(tableIdName.length()-1) == 's')
tableIdName = tableIdName.substring(0, tableIdName.length()-1);
//To read row
String rowID = rowDataList.get(0);
String selectSQL = "SELECT * FROM " +tableName +" "
+"WHERE " +tableIdName +"_ID = " +rowID;
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(selectSQL);
boolean value = result.next();
//INSERT # UPDATE row
if (value == true) { //Update Row if the data is already existed
updateStatementt(tableName, connection, rowDataList);
countUpdatedRow++;
}
else { //Insert New Row
insertStatementt(tableName, connection, rowDataList);
countNewRow++;
}
}
//Method to insert data to the database
static void insertStatementt(String tableType, Connection conn, ArrayList <String> rowDataList) throws SQLException, ParseException {
//Generate Question Mark
String generateQuestionMark = null;
if(rowDataList.size() == 1)
generateQuestionMark = "?";
else
generateQuestionMark = "?, ";
for(int i=1; i<rowDataList.size(); i++) {
if(i!=rowDataList.size()-1)
generateQuestionMark += "?, ";
else
generateQuestionMark += "?";
}
//Insert sql
String sql = "INSERT INTO " +tableType +" VALUES (" +generateQuestionMark +")";
PreparedStatement insertStatement = conn.prepareStatement(sql);
//Insert data
//There are other 'if' and 'else if' statements here for other tables
else if (tableType.equals("Tickets")) {
int ticketID = Integer.parseInt(rowDataList.get(0));
int movieId = Integer.parseInt(rowDataList.get(1));
int theaterId = Integer.parseInt(rowDataList.get(2));
String[] date = rowDataList.get(3).split("/");
String dateString = date[2] +"-" +date[1] +"-" +date[0];
Date showDate = Date.valueOf(dateString);
int showTimeId = Integer.parseInt(rowDataList.get(4));
int cptId = Integer.parseInt(rowDataList.get(5));
int pcId = Integer.parseInt(rowDataList.get(6));
float amountPaid = Float.parseFloat(rowDataList.get(7));
int year = Integer.parseInt(rowDataList.get(8));
String month = rowDataList.get(9);
insertStatement.setInt(1, ticketID);
insertStatement.setInt(2, movieId);
insertStatement.setInt(3, theaterId);
insertStatement.setDate(4, showDate);
insertStatement.setInt(5, showTimeId);
insertStatement.setInt(6, cptId);
insertStatement.setInt(7, pcId);
insertStatement.setFloat(8, amountPaid);
insertStatement.setInt(9, year);
insertStatement.setString(10, month);
}
insertStatement.executeUpdate();
insertStatement.close();
}
//Method to update the data from the database
static void updateStatementt(String tableType, Connection conn, ArrayList <String> rowDataList) throws SQLException {
Statement statement = conn.createStatement();
String sql = "UPDATE " +tableType;
//There are other 'if' and 'else if' statements here for other tables
else if (tableType.equals("Tickets")) {
String[] date = rowDataList.get(3).split("/");
String dateString = date[2] +"-" +date[1] +"-" +date[0];
sql += " SET movie_id = " +rowDataList.get(1) +","
+ " theater_id = " +rowDataList.get(2) +","
+ " showdate = \"" +dateString +"\","
+ " showtime_id = " +rowDataList.get(4) +","
+ " costperticket_id = " +rowDataList.get(5) +","
+ " personcategory_id = " +rowDataList.get(6) +","
+ " amount_paid = " +rowDataList.get(7) +","
+ " year = " +rowDataList.get(8) +","
+ " month = \"" +rowDataList.get(9) +"\""
+ " WHERE ticket_id = " +rowDataList.get(0);
}
statement.executeUpdate(sql);
}
}
For short, read a single line and do whatever you want to do with it. You don't have enough memory for all 700k lines.
You should add statement.close() for the update Statement.
If you really want to read all this data into the Java heap, increase the heap size using, for example, the -Xmx command-line switch. Because of the way textual data is encoded in the JVM, you'll probably need much more heap that the total data size would suggest.
In addition, there might be some places in your code where you can take the strain off the JVM's memory management system. For example, concatenating strings using "+" can generate a lot of temporary data, which will increase the load on the garbage collector. Assembling strings using a StringBuilder might be a simple, less resource-hungry, alternative.

How Do I load data from a CSV file to a table using java? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I have a File called Customer_Info.csv which has sample data like :
CUST_ID FIRST_NAME LAST_NAME USER_TYPE REPORTS_TO_ID EMAIL FIRST_TIME_LOGGED_IN FIRST_TIME_LOGIN_DATE ADDRESS_LINE1 ADDRESS_LINE2 CITY STATE ZIP
10001 MICHELLE VILLEGAS3 Savings SRINATH MICHELLE.VILLEGAS3#NOBODY.COM Y 07-10-18 1050 WEST FIFTH STREET AZUSA IND 917023308
This is the table in which i need to store the data. I am storing everything in string format because it is just a staging table.
Create Table Customer_Info_ST
(
Cust_ID varchar(5),
First_Name varchar(15),
Last_Name varchar(15),
User_Type varchar(10),
Report_To_Id varchar(10),
Email varchar(30),
First_Time_Logged_In varchar(1),
First_Time_Login_Date varchar(11),
Address_Line1 varchar(30),
Address_Line2 varchar(30),
City varchar(15),
State varchar(3),
Zip varchar(12)
);
I have written the following code to store it in the table.
public class CustInfoDataLoader {
static String sql, tableName;
private static PreparedStatement pstmt;
private static Statement stmt;
private static final String filePath = "Customer_Info.csv";
public static void main(String[] args) throws SQLException, FileNotFoundException, IOException, ParseException {
readCsv("Customer_info_ST"); //Line 24 in my code
//readCsvUsingLoad();
}
private static void readCsv(String tableName) throws FileNotFoundException, IOException, SQLException, ParseException {
CSVReader csvreader = null;
try{
Reader reader = Files.newBufferedReader(Paths.get(filePath));
csvreader = new CSVReaderBuilder(reader).withSkipLines(1).build();
sql = "insert into ? values (?,?,?,?,?,?,?,?,?,?,?,?,?)";
ManageDBResource.createConnectionToDB();
pstmt = ManageDBResource.conn.prepareStatement(sql);
String[] rowData = null;
while((rowData = csvreader.readNext()) != null) {
pstmt.setString(1, tableName);
int i = 2;
String state = rowData[11];
for (String data : rowData) {
if(i == 9 && data != null && state != "IND") {
java.text.SimpleDateFormat source = new java.text.SimpleDateFormat("MM-dd-yyyy");
java.util.Date date = source.parse(data);
java.text.SimpleDateFormat target = new java.text.SimpleDateFormat("yyyy-MM-dd");
data = target.format(date).toString();
}
pstmt.setString(i++,data);
//System.out.print(data + " ");
}
int result = pstmt.executeUpdate();
//System.out.println();
if(result == 1) {
System.out.println("Data loaded Successfully.");
}
}
}
catch (Exception e) {
System.out.println(e.getMessage());
}
finally {
pstmt.close(); //Line 69 in my code file
csvreader.close();
}
}
and I get the following error:
Exception in thread "main" java.lang.NullPointerException
at CustInfoDataLoader.readCsv(CustInfoDataLoader.java:69)
at CustInfoDataLoader.main(CustInfoDataLoader.java:24)
Can you close PreparedStatement after you executeUpdate()?
Like mentioned in the above example:
String sql = " INSERT INTO TABLE_(name,email,phone,id) VALUES(?,?,?,?) ";
try {
BufferedReader bReader = new BufferedReader(new
FileReader("1000rows.csv"));
String line = "";
while ((line = bReader.readLine()) != null) {
try {
if (line != null)
{
String[] array = line.split(",+");
for(String result:array)
{
System.out.println(result);
//Create prepared Statement here and set them and execute them
PreparedStatement ps = yourConnecionObject.createPreparedStatement(sql);
ps.setString(1,str[0]);
ps.setString(2,str[1]);
ps.setString(3,str[2]);
ps.setString(4,strp[3])
ps.excuteUpdate();
ps. close()
//Assuming that your line from file after split will follow that sequence
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
finally
{
if (bReader == null)
{
bReader.close();
}
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}

Text not being written to file

I cannot seem to figure this out. In the method below I'm trying to write a boolean to a file in 2 places, however nothing is actually being written. Any help would be greatly appreciated.
private void renameTables(){
String path = MessengerMain.getInstance().getDataFolder() + File.separator + "v3-0-0 Table Rename.txt";
File f = new File(path);
try(ResultSet rs = conn.getMetaData().getTables(null, null, "%", null); Writer w = new PrintWriter(new FileOutputStream(f, false))){
if (!f.exists()){
f.createNewFile();
w.write("false");
w.flush();
}
List<String> lines = Files.readAllLines(Paths.get(path));
if (lines.get(0).equalsIgnoreCase("false")){
System.out.println("[Messenger] Verifying table names...");
int count = 0;
List<String> tables = new ArrayList<String>();
tables.add("messages");
tables.add("scores");
tables.add("contacts");
while (rs.next()){
String table = rs.getString("TABLE_NAME");
if (tables.contains(table)){
update("ALTER TABLE " + table + " RENAME TO " + ("messenger_" + table) + ";");
count++;
}
}
if (count > 0){
System.out.println("[Messenger] Done. " + count + " table" + (count == 1 ? "" : "s") + " renamed.");
}else{
System.out.println("[Messenger] Done. No tables need to be renamed.");
}
w.write("true");
w.flush();
}
} catch (SQLException | IOException e){
e.printStackTrace();
}
}
Following Elliot Frisch's advice (same results):
private void renameTables(){
String path = MessengerMain.getInstance().getDataFolder() + File.separator + "v3-0-0 Table Rename.txt";
File f = new File(path);
try(ResultSet rs = conn.getMetaData().getTables(null, null, "%", null)){
Writer w = new PrintWriter(new FileOutputStream(f, false));
if (!f.exists()){
f.createNewFile();
w.write("false");
w.close(); //close here
}
List<String> lines = Files.readAllLines(Paths.get(path));
if (lines.get(0).equalsIgnoreCase("false")){
System.out.println("[Messenger] Verifying table names...");
int count = 0;
List<String> tables = new ArrayList<String>();
tables.add("messages");
tables.add("scores");
tables.add("contacts");
while (rs.next()){
String table = rs.getString("TABLE_NAME");
if (tables.contains(table)){
update("ALTER TABLE " + table + " RENAME TO " + ("messenger_" + table) + ";");
count++;
}
}
if (count > 0){
System.out.println("[Messenger] Done. " + count + " table" + (count == 1 ? "" : "s") + " renamed.");
}else{
System.out.println("[Messenger] Done. No tables need to be renamed.");
}
w = new PrintWriter(new FileOutputStream(f, false)); //create a new writer
w.write("true");
w.close(); //close here
}
} catch (SQLException | IOException e){
e.printStackTrace();
}
}
Here is a working full minimal, complete, verifiable example
public static void main(String[] args) {
File f = new File(System.getProperty("user.home"), "temp.txt");
String path = f.getPath();
try (Writer w = new FileWriter(f)) {
w.write("false");
} catch (IOException e) {
e.printStackTrace();
}
try {
List<String> lines = Files.readAllLines(Paths.get(path));
System.out.println(lines);
} catch (IOException e) {
e.printStackTrace();
}
}
Output is (as expected)
[false]

Exporting database to csv file with java

so i found this code on the internet, basically what supposedly it can do is backup all the tables from a db, my question is on this line:
res = st.executeQuery("select * from xcms." + tableName);
i get the following excpetion exception: SQLException information
what does xcms. stands for? what else can i put here?
res = st.executeQuery("select * from " + tableName);
btw if i erase xcms. and put it like this ^, i can save only the first table not all the tables, thx
the sourcecode webpage:
https://gauravmutreja.wordpress.com/2011/10/13/exporting-your-database-to-csv-file-in-java/#comment-210
public static void main(String[] args) {
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "gg";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "";
FileWriter fw;
try {
Class.forName(driver);
con = DriverManager.getConnection(url + db, user, pass);
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = 'gg'");
List<String> tableNameList = new ArrayList<String>();
while (res.next()) {
tableNameList.add(res.getString(1));
}
String filename = "C:\\Users\\Angel Silva\\Documents";
for (String tableName : tableNameList) {
int k = 0;
int j = 1;
System.out.println(tableName);
List<String> columnsNameList = new ArrayList<String>();
res = st.executeQuery("select * from " + tableName);
int columnCount = getColumnCount(res);
try {
fw = new FileWriter("C:\\Users\\Angel Silva\\Documents\\popo1121.csv");
for (int i = 1; i <= columnCount; i++) {
fw.append(res.getMetaData().getColumnName(i));
fw.append(",");
}
fw.append(System.getProperty("line.separator"));
while (res.next()) {
for (int i = 1; i <= columnCount; i++) {
if (res.getObject(i) != null) {
String data = res.getObject(i).toString();
fw.append(data);
fw.append(",");
} else {
String data = "null";
fw.append(data);
fw.append(",");
}
}
fw.append(System.getProperty("line.separator"));
}
fw.flush();
fw.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
con.close();
} catch (ClassNotFoundException cnfe) {
System.err.println("Could not load JDBC driver");
cnfe.printStackTrace();
}catch (SQLException sqle) {System.err.println("SQLException information");}
}
public static int getRowCount(ResultSet res) throws SQLException {
res.last();
int numberOfRows = res.getRow();
res.beforeFirst();
return numberOfRows;
}
public static int getColumnCount(ResultSet res) throws SQLException {
return res.getMetaData().getColumnCount();
}
}
This is what I used:
public void sqlToCSV (String query, String filename){
log.info("creating csv file: " + filename);
try {
FileWriter fw = new FileWriter(filename + ".csv");
if(conn.isClosed()) st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
int cols = rs.getMetaData().getColumnCount();
for(int i = 1; i <= cols; i ++){
fw.append(rs.getMetaData().getColumnLabel(i));
if(i < cols) fw.append(',');
else fw.append('\n');
}
while (rs.next()) {
for(int i = 1; i <= cols; i ++){
fw.append(rs.getString(i));
if(i < cols) fw.append(',');
}
fw.append('\n');
}
fw.flush();
fw.close();
log.info("CSV File is created successfully.");
conn.close();
} catch (Exception e) {
log.fatal(e);
}
}
The xms stands for the Database name, in your Connection in the java program you already are establishing the connection to the Database:
(DriverManager.getConnection(url + db, user, pass);
The string db is the name of the DB to connect to.
So no need to have the xms. .just for example use this query:
"SELECT * FROM "+tableName+";"
This is executed in the database you are connected to, for example ggin your code.
For writting the CSV file chillyfacts.com/export-mysql-table-csv-file-using-java/ may help!
SELECT * FROM <MENTION_TABLE_NAME_HERE> INTO OUTFILE <FILE_NAME> FIELDS TERMINATED BY ',';
Example :
SELECT * FROM topic INTO OUTFILE 'D:\5.csv' FIELDS TERMINATED BY ',';
use opencsv dependency to export SQL data to CSV using minimal lines of code.
import com.opencsv.CSVWriter;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class CsvWriter {
public static void main(String[] args) throws Exception {
CSVWriter writer = new CSVWriter(new FileWriter("filename.csv"), '\t');
Boolean includeHeaders = true;
Statement statement = null;
ResultSet myResultSet = null;
Connection connection = null;
try {
connection = //make database connection here
if (connection != null) {
statement = connection.createStatement();
myResultSet = statement.executeQuery("your sql query goes here");
writer.writeAll(myResultSet, includeHeaders);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}

How can I retrieve a column description from MS ACCESS database using Java

I am trying to retrieve column descriptions for MS Access columns using I am able to retrieve all columns of database like field name, data type.
I need description column data using Java.
Kindly give some suggestion or guidance.
Note: I used this code to get column name
public ArrayList<String> fetchtable(String value)
{
try
{
makeConnection();
String str1="Select * from "+ value;
ResultSet rs = st.executeQuery(str1);
rsmd = rs.getMetaData();
NumOfCol= rsmd.getColumnCount();
for(int i=1;i<=NumOfCol;i++)
{
ColumnName = rsmd.getColumnName(i);
System.out.println(ColumnName);
columns.add(ColumnName);
}
//System.out.println("Columns Valuessss is:" +columns);
}catch(Exception ae){
ae.printStackTrace();
}
return columns;
}
The only way I know to retrieve a field's Description is via Microsoft DAO. One way to do that would be to have the Java program
write a little VBScript,
execute it, and
capture the results,
something like this:
package com.example.getaccessfielddescription;
import java.io.*;
public class Main {
public static void main(String[] args) {
// test data
String dbFileSpec = "C:\\Users\\Public\\Database1.accdb";
String tableName = "Clients";
String fieldName = "LastName";
String vbsFilePath = System.getenv("TEMP") + "\\GetAccessFieldDescription.vbs";
File vbsFile = new File(vbsFilePath);
PrintWriter pw;
try {
pw = new PrintWriter(vbsFile);
pw.println("Set dbe = CreateObject(\"DAO.DBEngine.120\")");
pw.println("Set db = dbe.OpenDatabase(\"" + dbFileSpec + "\")");
pw.println("Set fld = db.TableDefs(\"" + tableName + "\").Fields(\"" + fieldName + "\")");
pw.println("WScript.Echo fld.Properties(\"Description\").Value");
pw.println("Set fld = Nothing");
pw.println("Set db = Nothing");
pw.println("Set dbe = Nothing");
pw.close();
Process p = Runtime.getRuntime().exec("cscript /nologo \"" + vbsFilePath + "\"");
p.waitFor();
BufferedReader rdr =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String fieldDescription = rdr.readLine();
vbsFile.delete();
System.out.println(fieldDescription);
} catch (Exception e) {
e.printStackTrace();
}
}
}

Categories