我正在AGAIN另一個程序,檢索來自我創建的數據庫字段的輸入的數據/值。但是這一次,我輸入的值將來自我創建的JtextField。我不知道這裏有什麼問題,因爲當我運行它時,輸出始終爲空。
在這個程序中,我會將我的JTextField的輸入值轉換爲int。這就是:
public class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == extendB)
{
ExtensionForm extend = new ExtensionForm();
extend.setVisible(true);
}
else if(e.getSource()== searchB)
{
//get text from the textField
String guest = guestIDTF.getText();
//parse the string to integer for retrieving of data
int id = Integer.parseInt(guest);
GuestsInfo guestInfo = new GuestsInfo(id);
Room roomInfo = new Room(id);
String labels[] = {guestInfo.getFirstName()+" "+guestInfo.getLastName(),""+roomInfo.getRoomNo(),roomInfo.getRoomType(),guestInfo.getTime(),"11:00"}; for(int z = 0; z<labels.length; z++) { labelDisplay[z].setText(labels[z]); }
在我的第二類
它就從我創建 這裏的數據庫字段的值輸入是程序代碼: 進口的java.sql。*;
公共教室 {
private String roomType;
private int guestID, roomNo;
private Connection con;
private PreparedStatement statement;
public Room(){
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/3moronsdb","root","");
}
catch (Exception e) {
e.printStackTrace();
}
}
public Room(int guestsID)
{
this();
try{
statement = con.prepareStatement("SELECT * FROM guest WHERE guestID=?");
statement.setInt(1, guestID);
ResultSet rs = statement.executeQuery();
while(rs.next()){
this.guestID = rs.getInt(1);
this.roomType = rs.getString(2);
this.roomNo = rs.getInt(3);
}
}catch(Exception e){
System.out.print(e);
}
}
//Constructor for setting rate
public Room(String roomType, int roomNo)
{
this();
try
{
statement = con.prepareStatement("Insert into room(roomType, roomNo) values(?,?)");
statement.setString(1, roomType);
statement.setInt(2, roomNo);
statement.executeUpdate();
}
catch(Exception e)
{
e.printStackTrace();
return;
}
}
//getting roomType
public String getRoomType(){
return roomType;
}
//getting roomNo
public int getRoomNo(){
return roomNo;
}
//getting guestID
public int getGuestId(){
return guestID;
}
}
我已經在我的3moronsdb它們是(1,經典,103)插入一些值。這裏是我的測試主類:
public class TestMain {
public static void main(String [] a){
GuestsInfo guest = new GuestsInfo(1); //note that this instantiation is the other class which i just
ask the other day.. (https://stackoverflow.com/questions/12762835/retrieving-values-from-database-in-java)
Room rum = new Room(1);
System.out.print(rum.getRoomType()+" "+ guest.getFirstName());
}
}
當我運行它,它只是給我的房類空輸出,但我得到的GuestsInfo類,這是「埃裏卡」的輸出。你能幫助我嗎?我知道我昨天問這種問題,但我現在真的不知道這裏有什麼問題..
我對'Room *類的SELECT * FROM guest WHERE guestID =?'好奇,不應該選擇從房間的桌子上?如果您在從結果集中檢索值時使用了列名,而不是使用列索引,那麼您應該選擇這種方法。有可能列索引可能會改變(對於名稱也可能是這樣),因爲順序取決於數據庫如何決定返回結果。 – MadProgrammer
@MadProgrammer你能給我一個關於你在說什麼的例子嗎?實際上,我使用select語句從數據庫中檢索數據。請。糾正我。 – NOOBprogrammer
@MadProgrammer說的是,如果你的SELECT語句是'SELECT fname,TABLE from lname',你應該使用rs.getString(「fname」)而不是rs.getString(1),因爲如果你把查詢改成'SELECT lname ,fname ...'rs.getString(1)你將不再檢索fname,但rs.getString(「fname」)會。 – jcern