当我从MyServ类调用getName时,我得到null,但是当我从DBClass本地调用它们时,它们返回字符串。谁知道我做错了什么?
package DB;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class DBClass{
private Statement stmt;
private Connection conn;
private ResultSet result;
public String name, surname;
public DBClass(){
}
public Connection dbConnect(final String db_connect_string,
final String db_userid,
final String db_password){
try{
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
conn =
DriverManager.getConnection(db_connect_string, db_userid,
db_password);
stmt = conn.createStatement();
result = stmt.executeQuery("Select * from .....etc");
if(result.next()){
name = result.getString(1).toString();
surname = result.getString(2).toString();
}
return conn;
} catch(final Exception e){
e.printStackTrace();
return null;
}
}
public String getName(){
return name;
}
public String getSurname(){
return surname;
}
}
package DB;
import java.io.IOException;
import java.sql.Connection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class MyServ
*/
public class MyServ extends HttpServlet{
private static final long serialVersionUID = 1L;
private final DBClass dbclass;
private final String name, surname;
private final Connection conn;
public MyServ(){
dbclass = new DBClass();
final DBClass db = new DBClass();
conn =
db.dbConnect("jdbc:oracle:thin:@elanweb:1510:xxxxx", "xxxxx",
"xxxxxx");
name = dbclass.getName();
surname = dbclass.getSurname();
}
@Override
protected void doGet(final HttpServletRequest request,
final HttpServletResponse response) throws ServletException,
IOException{
}
@Override
protected void doPost(final HttpServletRequest request,
final HttpServletResponse response) throws ServletException,
IOException{
System.out.println("MyServer -- " + name + " " + surname);
response.sendRedirect("http://localhost:8080/DWP/");
}
}
答案 0 :(得分:4)
当然你的意思是:
name = db.getName();
而不是:
name = dbclass.getName();
您似乎在构造函数中引用了错误的变量,没有打开的连接(dbclass)。
答案 1 :(得分:1)
只是因为值 null
( 是一个字符串,类型)。
查看代码的相关位。在MyServ
构造函数中,您可以:
dbclass = new DBClass();
根据DBClass构造函数,这会将所有字段初始化为默认值(字符串为null
)。
然后在调用之前不再使用此变量:
dbclass.getName();
正确地查找name
变量 - 它是null,因为它在构造对象时被隐式赋值为null - 并将其返回给你。
也许更好的问题是,你期望它返回什么,以及为什么?