可能重复:
从 java 中的数据库中检索值
我正在制作另一个程序,该程序从我创建的数据库中检索输入的字段数据/值。但是这一次,我输入的值将来自我创建的 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]); }
在我的第二堂课中,它从我创建的数据库中检索输入的字段值,代码如下: import 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,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 类的空输出,但我得到了 GuestInfo 类的输出,即“Ericka”。你们能帮帮我吗?我知道我昨天问了这种问题,但我现在真的不知道这里出了什么问题..