2017-07-27 110 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正在执行.. –