3

connecting to a mysql database from java using jdbc. declaring a query

String query = 
                    "SELECT *"+
                    "FROM tt2"+
                    "INTO OUTFILE 'DataFormatted.csv'"+
                    "FIELDS TERMINATED BY ','"+
                    "ENCLOSED BY '\"'" +
                    "LINES TERMINATED BY '\n'";

executing query using executQuery(query).

how to change above code to save DataFormatted.csv into c drive root directory

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
silverkid
  • 9,291
  • 22
  • 66
  • 92
  • I think this `query` will not work at all: missing separator (space) between lines. The concatenated query is `"SELECT *FROM tt2INTO OUTFILE 'DataFormatted.csv'FIELDS TERMINATED BY ','ENCLOSED BY '\"'LINES TERMINATED BY '\n'"` – user85421 Dec 11 '09 at 12:07
  • you are right .. i put the spaces finally – silverkid Dec 11 '09 at 12:50

3 Answers3

4

where is file getting saved.

In the current working directory of the MySQL server. Which one it is depends on how the MySQL server is executed and configured. Best is to change the location of the CSV file to a fixed location.

how to change above code to save DataFormatted.csv into c drive root directory

Just change 'DataFormatted.csv' by 'C:/DataFormatted.csv'.

Be aware that both Java code and the MySQL server should run at physically the same machine if you want to access the CSV file by Java as well. If they runs at physically different machines, then you'll probably look for other ways to access the CSV file, e.g. FTP'ing the generated CSV file.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • I think the working directory is wrong... at least it can not be the working directory of the Java process (unless there is some way of running MYSQL inside Java). – user85421 Dec 11 '09 at 12:36
2

Assuming your SQL query is correct (your example is missing spaces at line break), the OUTFILE saves the File on the server.
If no path is given, it will go in the Data Directory, in a subdirectory with the user's name.
It's something like the C:\Program Files\MySQLServer\data\test for the test user.

To find out what the data directory is, use the show variables where variable_name = 'datadir' query.

To change the location of OUTFILE just use the complete path, as suggested by BalusC.

user85421
  • 28,957
  • 10
  • 64
  • 87
0
SELECT ... INTO OUTFILE

dumps the data into a file on the MySQL server machine. If you want to create a local file on the Java client, you will need to create it yourself.

Avi
  • 19,934
  • 4
  • 57
  • 70