重複の可能性:
Javaでデータベースから値を取得する
作成したデータベースからフィールドの入力データ/値を取得する別のプログラムを再度作成しています。今回は、入力値は作成した JtextField から取得されます。私はそれを実行しているとき、出力が常にnullになるので、ここで何が問題なのだろうか。
このプログラムでは、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]); }
2 番目のクラスでは、作成したデータベースからフィールドの入力値を取得します。コードは次のとおりです。
パブリック クラス ルーム {
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、Classic、103)の値を挿入しています。ここに私のTESTメインクラスがあります:
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());
}
}
私がそれを実行していると、Room クラスの null 出力しか得られませんが、'Ericka' である GuestInfo クラスの出力を取得しています。みんな助けてくれませんか?昨日この種の問題を尋ねたことは知っていますが、今ここで何が問題なのか本当にわかりません..