将MYSQL行导出为多个txt文件

时间:2012-03-18 14:05:15

标签: mysql select

我有一个包含50.000行的MYSQL数据库。每行代表一篇文章。我希望将列名为“articletext”的列的值拆分为50.000个文件。每行一个文件。我是MYSQL的新手,所以我不知道该怎么做。

任何人都可以帮助我吗?

由于

2 个答案:

答案 0 :(得分:2)

我创建了这个小型java应用程序来解决这个问题。

        try {
        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("Opening connection");
        Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost/articles", "username", "password");

        String query = "Select title,articletext from articles";

        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(query);

        while (rs.next()) {
            String title = rs.getString(1);
            String text = rs.getString(2);

            try {
                FileWriter fstream = new FileWriter(title + ".txt");

                BufferedWriter out = new BufferedWriter(fstream);
                out.write(text);
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        System.out.println("Closing connection");
        con.close();

    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

答案 1 :(得分:2)

我建议使用Python解决方案:

import MySQLdb

def write_to_file(with_name, write_this):
    with_name = str(with_name)
    with open(with_name, "w") as F:
        F.write(write_this)

db = MySQLdb.connect(
   host="localhost",    # hostname, usually localhost
   user="andi",         # your username
   passwd="passsword",  # your password
   db="db_name",        # name of the database
   charset = "utf8",    # encoding
   use_unicode = True
) 

cur = db.cursor() 

cur.execute("select id, description from SOME_TABLE")

for row in cur.fetchall() :
    write_to_file(row[0], row[1].encode('utf8')) 

row[0]将映射到idrow[1]将映射到description