我正在将数据库中的元素添加到此stdData arrayList中。我在添加它们存在于stdData arrayList中后对其进行了检查,但是当我从另一个方法调用此stdData arrayList时(如您在此处看到的那样),它返回null。
package school;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ReadingStd {
String conURL = "jdbc:sqlserver://localhost:1433;" + "databaseName=schoolDB;user=fas;password=24071982";
List<String> stdData = new ArrayList<String>();
String std = null;
public void readStd(String stdId) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection(conURL);
System.out.println("faisal:");
String sqlQuery = "select * from schoolDB.dbo.addstudent where sid = '" + stdId + "'";
Statement stmt = con.createStatement();
System.out.println("faisal11:");
ResultSet rs = stmt.executeQuery(sqlQuery);
while (rs.next()) {
stdData.add(0, rs.getString("sid"));
stdData.add(1, rs.getString("name"));
stdData.add(2, rs.getString("fname"));
stdData.add(3, rs.getString("dob"));
stdData.add(4, rs.getString("classs"));
stdData.add(5, rs.getString("occupation_father"));
stdData.add(6, rs.getString("edu_father"));
stdData.add(7, rs.getString("email"));
stdData.add(8, rs.getString("father_office_address"));
stdData.add(9, rs.getString("cont1"));
stdData.add(10, rs.getString("occupation_mother"));
stdData.add(11, rs.getString("mother_office_address"));
stdData.add(12, rs.getString("mname"));
stdData.add(13, rs.getString("cont2"));
stdData.add(14, rs.getString("caddress"));
stdData.add(15, rs.getString("paddress"));
stdData.add(16, rs.getString("sex"));
stdData.add(17, rs.getString("addate"));
stdData.add(18, rs.getString("division"));
stdData.add(19, rs.getString("division"));
}
System.out.println(stdData.size());
con.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
public List < String > returnStd() {
return stdData;
}
public void printstd() {
System.out.println(stdData);
System.out.println(stdData.size());
}
public static void main(String[] args) {
new ReadingStd().readStd("czc");
new ReadingStd().printstd();
}
}
答案 0 :(得分:2)
问题在这里:
public static void main (String[] args) {
new ReadingStd().readStd("czc");
new ReadingStd().printstd();
}
列表是您实例化的对象中的一个字段。但是,您实例化了两个都有各自字段List<String> stdData
的对象,并通过调用readStd()
方法来填充该列表。您调用第一个对象的readStd()
方法,然后打印另一个未填充其自身列表的对象的列表。这将解决该问题:
public static void main (String[] args) {
ReadingStd reader = new ReadingStd();
reader.readStd("czc");
reader.printStd();
}
现在类型为reader
的对象ReadingStd
会在列表中填充这些值,并且同一对象会打印这些值。
答案 1 :(得分:1)
您实际上正在创建2个新对象。引起问题的。 更改
public static void main (String[] args) {
new ReadingStd().readStd("czc");
new ReadingStd().printstd();
}
到
public static void main (String[] args) {
ReadingStd r= new ReadingStd();
r.readStd("czc");
r.printstd();
}