我有返回陈述的问题>.<我想将所有杂志名称存储到
ArrayListListNameMagazine = new ArrayList ();
我有一个DB; 在数据库中有一个表name_magazine
,并在数据name_magazine
的
Magazine1
Magazine2
Magazine3
Magazine4
我的主要是:
ShowData Show = new ShowData(); int HowManyMagazine = Show.HowManyMagazine(1); // to make sure there is how many Magazine name in my database //System.out.print(HowManyMagazine); //i want to make sure the data is out. String nmeMagazine = null; // this variable for get data from return statement // i want to store in ListNameMagazine ArrayListListNameMagazine = new ArrayList (); for (int numbeer = 0;numbeer <= HowManyMagazine ; numbeer++) { //Store in 1 variable String, because if arrayList it's error nmeMagazine = Show.getResult("Select Name_Magazine from Magazine"); // Store again in array list ListNameMagazine.add(nmeMagazine); } for (String s : ListNameMagazine) { System.out.println(s); // show the data }
这是我的回复声明:
public String getResult(String sql) throws SQLException { ResultSet rs = st.executeQuery(sql); ResultSetMetaData resultsetmetadata = rs.getMetaData(); //String just_try = null; while (rs.next()) { System.out.println("Result:"+rs.getString(1)); //just_try = rs.getString(1); //return just_try; } return null; //return just_try; }
问题在于返回声明.
当注释(//)我擦除而最后一个返回null; 我删除了.它变得像这里:
public String getResult(String sql) throws SQLException { ResultSet rs = st.executeQuery(sql); ResultSetMetaData resultsetmetadata = rs.getMetaData(); String just_try = null; while (rs.next()) { //System.out.println("Result:"+rs.getString(1)); just_try = rs.getString(1); return just_try; } return just_try; }
当我使用此语句显示数据时.
for (String s : ListNameMagazine) { System.out.println(s); // show the data }
结果而已
Magazine4
Magazine4
Magazine4
Magazine4
@.@我迷惑@ @的地方.@
但是当我在这样的return语句中显示数据时
public String getResult(String sql) throws SQLException { ResultSet rs = st.executeQuery(sql); ResultSetMetaData resultsetmetadata = rs.getMetaData(); String just_try = null; while (rs.next()) { System.out.println("Result:"+rs.getString(1)); //just_try = rs.getString(1); //return just_try; } return null; }
数据显示了我想要的东西.我知道我只想念某个地方,但我不知道@.@.我希望你们能找到它.THX
你的问题是return只返回一件事,它会立即返回,函数将退出!你正在重新调整杂志的名称just_try.
while (rs.next()) { //System.out.println("Result:"+rs.getString(1)); just_try = rs.getString(1); return just_try; }
所以,你开始迭代rs,你得到的名字:
just_try = rs.getString(1);
然后你告诉代码返回just_try.
return just_try;
此时将返回just_try,函数将退出!我觉得你的问题是,你期待继续下去,并回头率值来调用它的代码的功能,但这不是它的工作方式.
我怀疑你想做的是这样的:
ArrayListListNameMagazine; ListNameMagazine = Show.getResult("Select Name_Magazine from Magazine");
然后在函数getResult中:
public ArrayListgetResult(String sql) throws SQLException { ResultSet rs = st.executeQuery(sql); ResultSetMetaData resultsetmetadata = rs.getMetaData(); ArrayList returnArrayList = new ArrayList (); while (rs.next()) { returnArrayList.add(rs.getString(1)); } return returnArrayList; }