我尝试创建csv
文件,以便在excel或liberoffice calc中使用它。但我有这个问题。
mysql> SELECT *
FROM formtable
INTO OUTFILE "/tmp/try.csv"
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '"'
LINES TERMINATED BY "\n";
如果我使用此命令,一切顺利。但是在服务器端,我不认为我在Linux中有像tmp文件夹这样的tmp文件夹。因此,我尝试在下面给出具体路径
mysql> SELECT *
FROM formtable
INTO OUTFILE "/var/www/try.csv"
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '"'
LINES TERMINATED BY "\n";
它给出了
ERROR 1 (HY000): Can't create/write to file '/var/www/try.csv' (Errcode: 13)
如果我将路径设为/home/blah/try.csv
,则存在相同的错误。你有什么建议吗?
答案 0 :(得分:0)
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import au.com.bytecode.opencsv.CSVWriter;
public class WriteCSV {
public static void main(String[] args) {
try {
String connectionURL = "jdbc:mysql://localhost:3306/test";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(connectionURL, "root", "root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select id_movie, movie_name from movies");
String csv = "E:\\dummyFolder\\output2.csv";
CSVWriter writer = new CSVWriter(new FileWriter(csv));
List<String[]> data = new ArrayList<String[]>();
while (rs.next())
{
data.add(new String[] { rs.getString(1), rs.getString(2) });
}
writer.writeAll(data);
System.out.println("CSV written successfully.");
writer.close();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e)
{
e.printStackTrace();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
您需要添加here
中的opencsv-2.3.jar答案 1 :(得分:0)
您应该检查权限。
ls -l /your/path
。
请注意,您的用户不应该有权写入所选文件夹,而是mysql
用户。您应该检查所有者,组,“其他”权限。
通常您可以在/tmp
文件夹中创建文件。