java 用java从数据库中检索值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12773076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
retrieving value from database in java
提问by NOOBprogrammer
Possible Duplicate:
retrieving values from database in java
可能的重复:
从 Java 中的数据库中检索值
I am making AGAIN another program that retrieves the inputted data/values of fields from the database I created. but this time, my inputted value will be coming from the JtextField I created. I wonder what's wrong in here bec when I'm running it the output is always null.
我正在制作另一个程序,从我创建的数据库中检索字段的输入数据/值。但这一次,我输入的值将来自我创建的 JtextField。我想知道这里有什么问题,当我运行它时,输出始终为空。
in this program i will convert the inputted value of my JTextField into int. here it is:
在这个程序中,我会将 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]); }
in my second class it retrieves the inputted values of fields from the database I created here's the code: import java.sql.*;
在我的第二堂课中,它从我创建的数据库中检索字段的输入值,代码如下: import java.sql.*;
public class Room {
公共课室{
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;
}
}
}
i already insert some values in my 3moronsdb which are ( 1, Classic , 103). here's my TEST main class:
我已经在我的 3moronsdb 中插入了一些值(1、经典、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());
}
}
when i'm running it it only gives me null output for the Room class but i am getting the output of the GuestsInfo class which is 'Ericka'. Can you help me guys? I know I ask this kind of problem yesterday but i really don't know what's wrong in here now..
当我运行它时,它只给我 Room 类的空输出,但我得到的是“Ericka”的 GuestInfo 类的输出。你能帮帮我吗?我知道我昨天问了这种问题,但我现在真的不知道这里出了什么问题..
回答by MadProgrammer
The select statement in this method looks wrong. Shouldn't it be selecting information from the Room
table??
此方法中的 select 语句看起来有误。不应该是从Room
表中选择信息吗??
public Room(int guestsID)
{
this();
try{
// This line looks wrong, shouldn't this be selecting from the
// room table??
// statement = con.prepareStatement("SELECT * FROM room WHERE guestID=?");
// instead???
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);
}
}
Instead of using the column indices to retrieval the values, you should be trying to use the column names. While probably very rare, it is possible that the the database may return columns in a different order then you are expecting in your code.
您应该尝试使用列名,而不是使用列索引来检索值。虽然可能非常罕见,但数据库可能会以与您在代码中期望的顺序不同的顺序返回列。
(This could happen for any number of reasons, the database is updated, the database is re-created, the DB engine is changes it mind... :P)
(这可能出于多种原因发生,数据库更新,数据库重新创建,数据库引擎改变主意......:P)
while(rs.next()){
this.guestID = rs.getInt("guestID");
this.roomType = rs.getString("roomType");
this.roomNo = rs.getInt("roomNumber");
}
Now, obviously, I know nothing about your database structure, so you'll need to update the column names appropriately. This would highlight when you make a mistake and select from the wrong table...
现在,显然,我对您的数据库结构一无所知,因此您需要适当地更新列名。当您犯错并从错误的表格中选择时,这将突出显示...
Also. You should be releasing your database resources when they are no longer needed
还。您应该在不再需要数据库资源时释放它们
PreparedStatement statement = null;
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);
} finally {
try {
statement.close();
}catch(Exception e){
}
}
Otherwise you run the risk of running out of database resources :P
否则,您将面临耗尽数据库资源的风险:P
I also wouldn't be creating a Connection
per class. I'd either create a single connection for the application or use a connection pool of some kind
我也不会为Connection
每个班级创建一个。我要么为应用程序创建一个连接,要么使用某种连接池