Issue
I have a database in XAMPP and I am using Eclipse IDE. I have to take the database contents and put them into a csv file. My code is not showing errors as such. It is executing perfectly.
I am not getting the output CSV file, in spite of the code working perfectly.
Here is my code:
import java.sql.*;
import java.io.*;
public class MainApp {
public static void main(String[] args)
{
String url = "jdbc:mysql://localhost:3306/userregistration";
String user = "root";
String password = "";
String csvFilePath = "Users-export.csv";
try (Connection con = DriverManager.getConnection(url, user, password)){
String sql = "SELECT * FROM usertable";
Statement stt = con.createStatement();
//Select DB
ResultSet res = stt.executeQuery(sql);
BufferedWriter fileWriter = new BufferedWriter(new FileWriter(csvFilePath));
// write header line containing column names
fileWriter.write("name,password");
while(res.next())
{
String Name = res.getString("name");
String Password = res.getString("password");
String line = String.format("\"%s\",%s",
Name, Password);
fileWriter.newLine();
fileWriter.write(line);
}
System.out.println("Successful");
stt.close();
fileWriter.close();
}
catch (SQLException e) {
System.out.println("Datababse error:");
e.printStackTrace();
} catch (IOException e) {
System.out.println("File IO error:");
e.printStackTrace();
}
}
}
Solution
The actual problem is that the output file's location was unknown--it should default to what ever the working directory is when you run your application. Check your application launcher in the Run -> Run Configurations... dialog. If that fails, create a java.io.File with your csv's file path and ask it for its canonical and absolute paths.
Answered By - nitind