2012-03-18 12 views
2

我有一个有50.000行的MYSQL数据库。每一行代表一篇文章。我想要将他们名为“articletext”的列的值分割为50.000个文件。每行一个文件。我是MYSQL的新手,所以我不知道该怎么做。将MYSQL行导出到几个txt文件中

任何人都可以帮助我吗?

谢谢

+1

这大概不能与MySQL独自完成。你能用一种编程语言吗? – 2012-03-18 14:09:48

+0

感谢您的回复。我可以创建一个连接到数据库的小型Java应用程序。这听起来像是最好的解决方案吗? – Peter 2012-03-18 14:12:48

+0

你肯定会需要另一种语言来完成程序部分--sql不是一种文件创建语言,它是一种查询语言。 – Randy 2012-03-18 14:12:54

回答

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(); 
    } 
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