2012-07-23 89 views
0

有人可以幫助我:我正在製作一個Java數據庫應用程序,並且希望將我的方法用於選擇,插入,更新和刪除到分離的類中,以便可以從其他類調用並重用它們。 到目前爲止,我設法只分離了更新和刪除的方法,以及在不使用準備好的語句時插入的方法。我遇到的問題是如何從數據庫中選擇並返回數據時返回數據。Java數據庫應用程序

這裏是我的更新和刪除在查詢類方法的:

import java.sql.Connection; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.sql.Statement; 
import com.Konekcija.Konekcija; 

public class Queries { 
Konekcija konekcija = new Konekcija(); 

public void updateTable(String sqlQuery){ 
    Connection conn = null; 
    Statement st = null; 
    try{ 
     Class.forName("com.mysql.jdbc.Driver"); 
     conn = konekcija.getConn(); 
     st = conn.createStatement(); 
     st.executeUpdate(sqlQuery); 

    }catch(Exception e){ 
     e.printStackTrace(); 
    }finally{ 
     try { 
      conn.close(); 
     } catch (SQLException e) { 
      e.printStackTrace(); 
     } 
     try { 
      st.close(); 
     } catch (SQLException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

public void deleteFromTable(String sqlQuery){ 
    Connection conn = null; 
    Statement st = null; 
    try{ 
     Class.forName("com.mysql.jdbc.Driver"); 
     conn = konekcija.getConn(); 
     st = conn.createStatement(); 
     st.executeUpdate(sqlQuery); 
    }catch(Exception e){ 
     e.printStackTrace(); 
    }finally{ 
     try { 
      conn.close(); 
     } catch (SQLException e) { 
      e.printStackTrace(); 
     } 
     try { 
      st.close(); 
     } catch (SQLException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

} 

附:連接屬性在另一個類「Konekcija」

回答

1

你應該創建一個集合,並與查詢的結果填充它,它應該是這個樣子:

List<Foo> selectFoos(Connection connection) throws SQLException { 
    PreparedStatement ps = connection.prepareStatement("select * from foo"); 
    try { 
     ResultSet resultSet = ps.executeQuery(); 
     try { 
      List<Foo> foos = new ArrayList<Foo>(); 
      while (resultSet.next()) { 
       Foo foo = new Foo(); 
       // use resultSet methods get... to retrieve data from current row of results 
       // and populate foo 
       foos.add(foo); 
      } 
     } finally { 
      resultSet.close(); 
     } 
    } finally { 
     ps.close(); 
    } 
    return foos; 
} 
0

「從表中選擇」的返回數據將是ResultSet

  1. 您可以返回結果集呼叫者,而得到的值(或)
  2. 裏面的「選擇」查詢類的方法從ResultSet中檢索數據,並設置一些VO對象與此VO加至收集和返回集合(假設您將在ResultSet中獲得多行)。例如,如果您要查詢用戶表,請使用get/set方法創建Java bean類「User」。將檢索到的值設置爲此bean並將其返回。 //在某些包中使用get/set創建用戶類。

    Class.forName("com.mysql.jdbc.Driver"); 
        conn = konekcija.getConn(); 
        st = conn.createStatement(); 
        ResultSet rs=st.execute(sqlQuery); 
        //Instantiate user class 
         while (rs.next()) 
        System.out.println("Name= " + rs.getString("moviename") + " Date= " +    String fName = rs.getString("firstName"); 
    

    User myUser = new User(); myUser.setFirstName(fName); }

    NOTE:此代碼是手工輸入的。可能有語法錯誤。請用它作爲出發點。

+0

@NathanHughes:這就是我的第二點建議。 – kosa 2012-07-23 21:23:36

+0

我也在想那個,但我不知道這麼做。 – 2012-07-23 21:25:35

+0

@ brano88:用示例更新了我的答案。 – kosa 2012-07-23 21:31:47