2017-07-27 104 views
0

我正在嘗試將數據從數據庫寫入文本文件。將數據從數據庫寫入Java文件

文本文件保持空白。我試圖去。下面是代碼:

public void writeText() 
{ 
    try 
    { 
     Class.forName("com.mysql.jdbc.Driver"); 
    } 
    catch(Exception e) 
    { 
     e.printStackTrace(); 
    } 
    final String DB_URL ="jdbc:mysql://mis-sql.uhcl.edu/gattupalliv3940"; 
    Connection conn = null; 
    Statement stat = null; 
    ResultSet rs = null; 
    try 
    { 
     conn = DriverManager.getConnection(DB_URL,"gattupalliv3940","1552688"); 
     stat = conn.createStatement(); 
     rs = stat.executeQuery("select * from student_2"); 
     FileWriter fw = new FileWriter("data.txt"); 
     BufferedWriter bw = new BufferedWriter(fw); 
     String line =""; 
     while(rs.next()) 
     { 
      line = rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getDouble(3); 
      bw.write(line); 
      bw.newLine(); 
     } 
     bw.close(); 
    } 
    catch(Exception e) 
    { 
     e.printStackTrace(); 
    } 
    finally 
    { 
     try 
     { 
      conn.close(); 
      rs.close(); 
      stat.close(); 
     } 
     catch(Exception e) 
     { 
      e.printStackTrace(); 
     } 
    } 
} 
+0

爲什麼不使用JPA進行數據庫訪問?這是一個Java SE項目嗎? – KG6ZVP

+0

請說明你已經試圖解決這個問題,否則在一些基本的**調試**技術上會出現一個巨大的乒乓球。首先來這裏:儘量減少代碼並附上問題。你的文件編寫代碼甚至工作嗎?你沒有嘗試過所有這些SQL的東西,只是測試你的代碼是否能夠將一個給定的'String'寫入文件。之後檢查你的數據庫是否真的包含一些東西。然後檢查你的查詢結果是不是空的,等等。某處必須是錯誤,通過附上它來找到它。 – Zabuza

+0

它是一個Java EE項目。結果集不是空的。它在SE項目中嘗試了相同的代碼,並且工作正常。 –

回答

0

如果你沒有得到任何錯誤,該文件是空的,可以發生的唯一的事情就是你的,而(rs.next())線必須返回false第一通過時間;這意味着你沒有從數據庫中獲得任何東西。

您是否已經通過代碼來驗證哪些行正在執行以及哪些行不是?

我懷疑這個文件沒有寫到你期望的地方,因爲你沒有指定一個目錄。我創建了一個簡單的測試,並將文件寫入Tomcat的目錄中... \ springsource \ vfabric-tc-server-developer-2.6.4.RELEASE \ spring-insight-instance \ wtpwebapps \ Junk \ data.txt(我的項目被命名爲Junk)。下面是我的代碼(沒有數據庫的東西):

@RequestMapping(value="/") 
public ModelAndView test(HttpServletRequest request, HttpServletResponse response) throws IOException{ 

    writeText(request.getRealPath("data.txt")); 

    return new ModelAndView("home"); 
} 

public void writeText(String path) { 
    BufferedWriter bw = null; 
    try { 
     FileWriter fw = new FileWriter(path); 
     bw = new BufferedWriter(fw); 
     String line = "this is only a test"; 
     bw.write(line); 
     bw.newLine(); 
    } 
    catch(Exception e) { 
     e.printStackTrace(); 
    } finally { 
     if(bw != null) { 
      try { 
       bw.close(); 
      } catch (IOException e) { 
       // ignore 
      } 
     } 
    } 
} 
+0

yes。 bw.write正在執行.. –