Export Access Database to text File Java - java

I am trying to create text file from Select * of access mdb file, I wrote below code to implement same, but while I am trying to read the data I am getting this error "Exception in thread "main" java.sql.SQLException: [Microsoft][ODBC Driver Manager] Invalid descriptor index"
Not sure if this method will actually work, here's the code:
//=============Extract contents in Access and save it as Text File Format==========================================
//String connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\test\\TestEJFolder\\BWC_Ejournal.mdb";
String connectionString ="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}; DBQ=C:\\test\\TestEJFolder\\BWC_Ejournal.mdb;";
DriverManager.getConnection(connectionString, "", "");
Connection conn = DriverManager.getConnection(connectionString, "", "");
String sql = "SELECT * FROM Events";
Statement cmd = conn.createStatement();
cmd.execute(sql);
ResultSet reader = cmd.executeQuery(sql);
//String path = "\\" + time_stmp + "_" + file_name;
File sw = new File(text_dir,file_name);
File ssw = new File(s_path);
sw.createNewFile();
final String format = "{0,-22} {1,-4} {2,-4} {3,-4} {4,-20} {5,-22}";
BufferedWriter output = new BufferedWriter(new FileWriter(sw));
String line = null;
//reader.beforeFirst();
//boolean b = true;
int colCount = rs.getColumnCount();
while (reader.next())
{
//Errors here while trying to read
line = String.format(format, String.format("{0:dd-MM-yyyy HH:mm:ss}", reader.getObject(5)).trim(), reader.getObject(0).toString().trim(), reader.getObject(1).toString().trim(), reader.getObject(2).toString().trim(), reader.getObject(3).toString().trim(), reader.getObject(4).toString().trim());
}
output.write(line);
output.close();
conn.close();

There is a problem at the String.format. Check out Java Tutorial on Strings:
Creating Format Strings
You have seen the use of the printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object.
Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example, instead of
System.out.printf("The value of the float " +
"variable is %f, while " +
"the value of the " +
"integer variable is %d, " +
"and the string is %s",
floatVar, intVar, stringVar);
you can write
String fs;
fs = String.format("The value of the float " +
"variable is %f, while " +
"the value of the " +
"integer variable is %d, " +
" and the string is %s",
floatVar, intVar, stringVar);
System.out.println(fs);

Excerpt from your code:
...reader.getObject(0).toString().trim()
AFAICT, you are expected to pass column index starting from 1 to getObject method. I'm not sure what are you trying to get there.
P.S. Next time pay attention to code formatting (remove all of the empty lines, comments, unnecessary statements), post stack trace and highlight clearly the line throwing an exception.

1.Try to separate the test to a small unit of function
1.1 read from DB into object(if you have the time try to use hibernate)
1.2 try to print the object
1.3 try to write to file
see that every unit
i see some problems :
1.the Date should be Date object and not String
2.you have more then one connection

Related

LDAP with Jacob-ADO-Wrapper

after a little bit of trying I managed to get results from the ldap-server at my company. Now I have a little problem and I seem to be too dump to find any documentation about it.
Command objCmd = new Command();
Recordset RS = new Recordset();
objCmd.setActiveConnection(conn);
objCmd.setCommandText("<LDAP://scdldap.siemens.net:389>;(&(objectClass=scdInternetPerson)(mail=" + email + "));" +searchKeyword+";subTree");
RS = objCmd.Execute();
if (RS.getBOF())
System.out.printf(email + ";" + "null" + "\n");
else {
RS.MoveFirst();
System.out.printf(email + ";" + RS.getFields().getItem(0).getValue() + "\n");
}
This works fine as long as I print the result out to the console. But I would need to get the value as a String (it is always a String), but I can't make it. Can somebody tell me what I am missing? I know this is some VariableType Error, because the result is of type Variant, but
Variant.toString() or anything else is not possible.
Try to convert Variant to Object and then to String, for example:
Variant From = new Variant(1);
Variant To = new Variant(6);
Object[] args = new Object[]{From, To};
String From1 = args[0].toString();
String To1 = args[1].toString();

Java Hard Coded SQL Query works but the exact same query read from a file buffer fails

I am using Java and MySQL. This code works and returns the expected results:-
queryStr = "SELECT PROGRAM, EQUIPMENT, t.PART_NUMBER, SN, GFE_CAP, t.STATUS, ii.Part_Number, ii.Serial_Number, [Inventory_Type – Level 1], ii.Status, ii.Destination, ii.Location" +
" FROM tblGFE_CAP as t, NGC_BJ_DEV.dbo.ISSUE_ITEMS as ii" +
" WHERE (t.PART_NUMBER = ii.Part_Number)" +
" AND (SN = ii.SERIAL_NUMBER)" +
" AND (GFE_CAP != [Inventory_Type – Level 1])" +
" AND NOT (([Inventory_Type – Level 1] = 'GFP') and (GFE_CAP = 'GFE'))" +
" AND NOT ((ii.Status = 'Retired') AND (t.Status = 'INACTIVE-REPLACED/RETIRED/DISPOSITION'))" +
" AND NOT ((ii.Status = 'Consumed') and (t.Status = 'INACTIVE-REPLACED/RETIRED/DISPOSITION'))" +
" GROUP BY PROGRAM, EQUIPMENT, t.PART_NUMBER, SN, GFE_CAP, t.Status, ii.Part_Number, ii.Serial_Number, [Inventory_Type – Level 1], ii.Destination, ii.Location, ii.Status" +
" ORDER BY GFE_CAP, t.PART_NUMBER, SN";
stmt = con.prepareStatement(queryStr);
rs = stmt.executeQuery();
However, if I read the exact same text from a file (as below) and copy the results into queryStr, the code chokes on the Inventory_Type - Level 1 column name. I confirmed that the resultant strings are identical when passed to preparedStatement. I understand that special characters are not a good idea for the column name, but that is beyond my control.
I cannot change the column name. My real question is why the hard coded query works but the file read does not. Alternatively if there is a syntax that can be used to capture the column name within the java built query string.
String bStr = "";
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(in.getAbsolutePath()));
while (true)
{
bStr = br.readLine();
if (bStr == null)
break;
sb.append(bStr);
}
br.close();
queryStr = sb.toString();
stmt = con.prepareStatement(queryStr);
rs = stmt.executeQuery();
Use sb.append(bStr).append("\n") instead of sb.append(bStr).
Your current code lose line breaks and probably two different words from adjusting lines become one.
This issue has to do with the fact that you are trying to read in special characters (in this case brackets) using your buffered reader. That problem has already been addressed.
see the following approaches:
Read/write .txt file with special characters
Read special characters in java with BufferedReader

How should I get this specific text from str?

I have a lot of strings in database like this : "\\LDDESKTOP\news\1455Bloomberg Document # 180784.txt". I want to get the file name after the last slash.
I do this just in a normal way :
str.substring(str.lastIndexOf("\\")+1)
But it doesn't work because the single slash is used for change meanings. Is there a way in java just like python to tell compiler to regard it as a plain string like this , str=r'.......' .
Or how to change the string to "\\\\LDDESKTOP\\news\\1455Bloomberg Document # 180784.txt". So I can pass it to File Object to read this file.
how should I do this? Or other ways to solve this.
Thanks.
The column named path(varchar(150)) in the news table is like this "\LDDESKTOP\news\1362Bloomberg Document # 180691.txt"
And I do a normal select on the path.
the code :
public List<String> getNewsFileName(String startTime,String endTime) {
List<String> newsFileNames = new ArrayList<String>();
String tableName = ConfigFile.getConfig("configuration.txt","SQLServerTable");
String sql = "select Path from [" + tableName + "] where localtime >= '" + startTime + "' and localtime <= '" + endTime + "'";
try {
if(connection==null) {
InvertedIndex.logger.log(Level.SEVERE, "Database connection has not been initialized");
System.exit(-1);
}
stmt=connection.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
String path=rs.getString(1);
newsFileNames.add(path);
}
} catch (SQLException e) {
InvertedIndex.logger.log(Level.SEVERE,"Fail to store news");
}
return newsFileNames;
}
You use Escape Sequences to specify certain special characters that also have java properties assigned to them.
In order to print a single backslash character in a string you use a set of 2 backslashes \\.
String string = new String("\\\\LDDESKTOP\\news\\1455Bloomberg Document # 180784.txt");
String str = string.substring(string.lastIndexOf("\\")+1);
System.out.println(str);
This prints
1455Bloomberg Document # 180784.txt
Edit 1:
Once you have the string, you can pass it back using the same escape character.
String string = "\\\\LDDESKTOP\\news\\" + str;
This outputs the original
\\LDDESKTOP\news\1455Bloomberg Document # 180784.txt
Edit 2:
Based on what you asked, in order to transform all single backslashes into double backslashes you must use both the escape sequence and the string "replace" method.
If you have this string:
String string = new String("\\\\LDDESKTOP\\news\\1455Bloomberg Document # 180784.txt");
You need to call this code to "double" every backslash:
String newString = string.replace("\\", "\\\\");
This produces the following:
//Note this is before we print it. This illustrates all the escape sequences.
\\\\\\\\LDDESKTOP\\\\news\\\\1455Bloomberg Document # 180784.txt
The string itself will look like this:
\\\\LDDESKTOP\\news\\1455Bloomberg Document # 180784.txt
this code :
String st = "\\LDDESKTOP\news\1455Bloomberg Document # 180784.txt";
st = st.replace("\n", "\\n");
st = st.replace("\\", "\\\\");
String str = st.substring(st.lastIndexOf("\\")+1);
test it.
"\n" is line break.
Thanks for all the efforts you have made . Finally , I think I have found the answer.
Instead of dealing with the string in java program, I process the string using sql functions directly.
Following is what I do.
SELECT * substring(path,len(path)-charindex('\',reverse(path))+2,charindex('\',reverse(path)))
FROM News
This really does a good job !!

uncaught syntax error

I am using following code for local storage.
for(int i=0; i< files.length; i++)
{
System.out.println("base = " + files[i].getName() + "\n i=" +i + "\n");
AudioFile f = AudioFileIO.read(files[i]);
Tag tag = f.getTag();
//AudioHeader h = f.getAudioHeader();
int l = f.getAudioHeader().getTrackLength();
String s1 = tag.getFirst(FieldKey.ALBUM);
out.print("writeToStorage("+s1+","+s1+");");
}
getting uncaught syntex erroe: unexpected identifer as a error.
Im guessing you meant java rather than javascript?
Your unexpected identifier is here out.println you need System. infront of it.
The reason for this is that out is not defined in your code. You need to access it by using the static variable in the System class. Hence why you use System.out.
Alternatley you could set a variable out to be equal to System.out for shorthand, although I don;t tend to. But this can allow you to switch out to a different type of output stream without having to refactor your code much.
Have you added following ?
import static java.lang.System.out;
Probably you need to output "s in the last line to surround the s1 values.
"writeToStorage("+s1+","+s1+");"
->
"writeToStorage('"+s1+"','"+s1+"');"
Btw for the same reason you have to fix the other line too:
"base = " + files[i].getName() + "...
->
"base = '" + files[i].getName() + "'...

Split a string in Java

I have a function that accepts a message in String form. The message looks like this : "HTTP/1.1 GET /1/ \n"
I have been using the java.String.split method to break down the string into three smaller substrings, version, command, and number. Then I reconstruct the oringal string from the substrings and output it.
However, when I run teh function the program results in ArrayIndex out of bounds : 1, but still functions properly. But when I run the program step by step in the debugger (netbeans) the program does not result in the ArrayIndex out of bounds nonesense and functions as normal
Any suggestions?
Sam
String output = "";
String[] tokens = clientMessage.split(" ");
String version = tokens[0];
String command = tokens[1];
String potNum = tokens[2];
output = version + " " + command + " " + potNum;
EDIT yes, the program is multithreaded, the clientMsessage string contains "HTTP/1.1 GET /1/ \n" all the time, the value fo clientMessage never changes. The clientMessage is a string sent from a client program and then processed on the server and the output is snet back tot eh client but I keep getting the array errors
I suggest you print out/log your inputs. I suspect you are doing something differently when you debug your program. Its possible this works the first time you call it but when its called again, it fails.
Add before the split.
System.out.println("clientMessage >" + clientMessage +"<");
If your output looks like
clientMessage >HTCPCP/1.0 PROPFIND /1/<
clientMessage >HTCPCP/1.0 PROPFIND /1/<
clientMessage ><
It appears you have an empty request message. I imagine this means the client will not be sending more requests and you have to handle this differently.
ArrayIndexOutOfBounds arises when you are accessing index of an array which does not have any values means in your case tokens[1] does not exists. When debugging are you using same string as input??
Sorry this is not an answer but just an additional question to find what is actually wrong and comments are too small to put that much code. The following works for me, so one of your asumptions is wrong:
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
String clientMessage = "HTTP/1.1 GET /1/ \n";
String[] tokens = clientMessage.split(" ");
String version = tokens[0];
String command = tokens[1];
String potNum = tokens[2];
System.err.println(version + " " + command + " " + potNum);
}
}
It runs OK on my side. I would have to guess that sometimes clientMessage is a value that does not contain enough spaces to be seperated in 3 parts.
Perhaps there is more to the code than you are including here. I put your code in a class as follows and it compiles and runs without error. Is there something missing?
public class Andrew {
public static void main(String args[]) {
String output = "";
String clientMessage = "HTTP/1.1 GET /1/ \n";
String[] tokens = clientMessage.split(" ");
String version = tokens[0];
String command = tokens[1];
String potNum = tokens[2];
output = version + " " + command + " " + potNum;
System.out.println(output);
}
}

Categories